Exceptions and week 7 review
A robust program must decide what to do when something goes wrong: a file that does not exist, a badly typed number, an insufficient balance. Returning error codes forces you to check them at every call, and it is easy to forget. Exceptions offer another path: whoever detects the problem throws an error object, execution jumps back through the calling functions and stops at the first catch block that knows how to handle it. In between, the destructors of local objects run, so if you used RAII the cleanup is automatic. That is why RAII and exceptions are a pair.
try, throw and catch
The code that may fail goes inside a try block; each catch declares which type of exception it catches. The standard library defines a hierarchy in <stdexcept>, with std::exception at the root and classes like std::invalid_argument, std::out_of_range and std::runtime_error, all with the what() method that returns the message. A golden rule: always catch by const reference (catch (const std::exception& e)) to avoid copies and the slicing we saw in week 6. The catch blocks are evaluated in order, so put the most specific types first and the most general last. With catch (...) you catch anything, but you will not know what happened.
#include <iostream>
#include <stdexcept>
#include <string>
int parseAge(const std::string& text) {
int value = std::stoi(text); // throws std::invalid_argument if not a number
if (value < 0 || value > 150) {
throw std::out_of_range{"age out of range: " + text};
}
return value;
}
int main() {
const std::string inputs[] = {"42", "abc", "200"};
for (const std::string& in : inputs) {
try {
std::cout << "age = " << parseAge(in) << '\n';
} catch (const std::invalid_argument&) {
std::cout << "'" << in << "' is not a number\n";
} catch (const std::exception& e) { // general handler goes last
std::cout << "error: " << e.what() << '\n';
}
}
// age = 42
// 'abc' is not a number
// error: age out of range: 200
return 0;
}Custom exceptions and automatic cleanup
For errors from your program's domain create a class that inherits from std::runtime_error (or std::exception). That way users can catch it specifically or as a standard exception. In the following example, the InsufficientFunds exception leaves withdraw, crosses the transfer function and is caught in main; meanwhile, the local Tracer object of transfer is destroyed correctly. Also notice noexcept: it marks a function that promises not to throw; if it breaks the promise, the program terminates. Destructors are noexcept by default, so never throw from them.
#include <iostream>
#include <stdexcept>
#include <string>
class InsufficientFunds : public std::runtime_error {
public:
explicit InsufficientFunds(double missing)
: std::runtime_error{"missing " + std::to_string(missing)}, missing_{missing} {}
double missing() const noexcept { return missing_; }
private:
double missing_;
};
struct Tracer {
~Tracer() { std::cout << "cleanup done\n"; }
};
void withdraw(double& balance, double amount) {
if (amount > balance) {
throw InsufficientFunds{amount - balance};
}
balance -= amount;
}
void transfer(double& from, double amount) {
Tracer tracer; // RAII: destroyed even if an exception passes through
withdraw(from, amount);
std::cout << "transfer ok\n";
}
int main() {
double balance{100.0};
try {
transfer(balance, 30.0); // cleanup order: transfer ok, cleanup done
transfer(balance, 500.0); // throws
} catch (const InsufficientFunds& e) {
std::cout << "failed, missing " << e.missing() << '\n'; // missing 430
}
return 0;
}
// output: transfer ok / cleanup done / cleanup done / failed, missing 430Week 7 review: templates let you write generic code once; lambdas define small functions at the point of use, with explicit capture; STL algorithms (sort, count_if, find_if, transform, accumulate) replace manual loops; unique_ptr expresses exclusive ownership and shared_ptr shared ownership; exceptions separate the normal path from the error path, relying on RAII to clean up. Typical mistakes: catching by value, throwing from a destructor, using an exception for the normal flow of the program and forgetting to check find_if against end().
Проверьте себя
Вопрос 1 из 6How should an exception normally be caught?
✎ Мои заметки
Сохранено только в этом браузере. Войдите, чтобы хранить в аккаунте.0/5000 символов