An exception reports an error by transferring control to a handler. The control flow is as follows:
throwraises an exception.- The rest of the
tryblock is skipped, and the call stack is unwound back to it. - The first matching
catchblock runs, then the program continues after the try-catch block.
If nothing catches the exception, the program terminates:
#include <stdexcept>
double divide(double a, double b) {
if (b == 0) {
throw std::invalid_argument#include <stdexcept>("Division by zero.");
}
return a / b;
}
try {
divide(1, 0);
} catch (const std::invalid_argument#include <stdexcept>& e) {
// e.what() returns the exception's message.
std::cout#include <iostream> << e.what() << "\n"; // Division by zero.
}Note
Catch exceptions by const&. Catching by value copies the exception, and slices derived exceptions caught as their base type.
When an exception is thrown, the call stack is unwound:
void f() {
std::vector#include <vector><int> v(100);
throw std::runtime_error#include <stdexcept>("Oops.");
} // v is destroyed before the exception leaves f.Warning
Don't throw exceptions from a destructor. If a destructor throws during stack unwinding, the program terminates.
The standard exceptions all derive from std::exception#include <exception>. The most common ones come from the stdexcept header:
std::runtime_error#include <stdexcept>for errors that can only be detected while the program runs.std::logic_error#include <stdexcept>for bugs that could have been caught before running. Deriving fromstd::logic_error#include <stdexcept>are:std::invalid_argument#include <stdexcept>for an argument with a value the function doesn't accept, such asdivide(1, 0)above.std::out_of_range#include <stdexcept>for an index or value outside the allowed range, such asv.at(10)on a vector of 3 elements.
A try block can have multiple catch blocks for different types of exceptions. These catch blocks are checked in the order they are written:
try {
std::vector#include <vector><int> v;
v.at(0);
} catch (const std::out_of_range#include <stdexcept>& e) {
std::cout#include <iostream> << "Out of range: " << e.what() << "\n";
} catch (const std::exception#include <exception>& e) {
std::cout#include <iostream> << "Other error: " << e.what() << "\n";
}Note
Write the more specific exception types first, otherwise a catch for a base class would catch the exception first.
The catch-all handler is catch (...), which catches any exception:
try {
throw std::runtime_error#include <stdexcept>("Oops.");
} catch (...) {
}throw; rethrows the current exception from inside a catch block:
try {
throw std::runtime_error#include <stdexcept>("Oops.");
} catch (...) {
throw;
}Custom Exception
Custom exceptions usually derive from a standard exception, so they can still be caught as std::exception#include <exception>:
class ParseError : public std::runtime_error#include <stdexcept> {
public:
ParseError(const std::string#include <string>& msg) : std::runtime_error#include <stdexcept>(msg) {}
};
try {
throw ParseError("Expected a number.");
} catch (const ParseError& e) {
std::cout#include <iostream> << e.what() << "\n"; // Expected a number.
}noexcept marks a function that is not allowed to throw. If it throws, the program terminates instead of passing the exception to the caller:
int add(int a, int b) noexcept {
return a + b;
}Note
Destructors and operator delete are implicitly noexcept.
References
- cppreference: throw
- cppreference: try block
- cppreference: std::exception
- cppreference: noexcept specifier
Dan