C++ Exceptions
Exceptions provide a way to handle runtime errors gracefully using `try`, `throw`, and `catch` blocks, instead of crashing the whole program. Code that might fail goes in a `try` block; if it throws, control jumps to a matching `catch` block.
The standard library provides exception types like `std::runtime_error` and `std::out_of_range` under `<stdexcept>`, and you can also define your own custom exception classes.
try/throw/catch
`try { ... throw std::runtime_error("oops"); } catch (const std::exception& e) { std::cout << e.what(); }` catches and handles the error using its message.
Custom exceptions
You can throw any type, but it's conventional to derive custom exception classes from `std::exception` and override `what()` to describe the error.
try {
throw std::runtime_error("Something failed");
} catch (const std::exception& e) {
std::cout << e.what();
}Something failedThe catch block receives the exception and prints its message via what().
try {
int arr[3] = {1,2,3};
if (5 >= 3) throw std::out_of_range("bad index");
} catch (const std::out_of_range& e) {
std::cout << "Caught: " << e.what();
}Caught: bad indexA specific exception type can be caught and handled distinctly.
Key points
- try/throw/catch handle runtime errors gracefully.
- <stdexcept> provides common exception types like runtime_error.
- catch (const std::exception& e) can catch most standard exceptions.
- Custom exceptions typically derive from std::exception.
