Exception Handling
Prerequisites: STL algorithms
Unlike C's manual return-code checking, C++ has real exceptions —
throw an object (conventionally derived from
std::exception), and catch it anywhere up the call stack.
#include <stdexcept>
double divide(double a, double b) {
if (b == 0) {
throw std::invalid_argument("Cannot divide by zero");
}
return a / b;
}
try {
std::cout << divide(10, 0) << std::endl;
} catch (const std::invalid_argument &e) {
std::cout << "Error: " << e.what() << std::endl;
}
Catch by const & (as above) rather than by value — catching by
value copies the exception object unnecessarily and can slice a
derived exception type down to its base.
Common mistakes
- Throwing an exception out of a destructor — during stack unwinding from another exception, this can terminate the program immediately rather than propagating cleanly.