The standard hierarchy of exception classes, all derived from std::exception. Always catch by const reference.
Include: #include <stdexcept> | Namespace: std | Compile: g++ -Wall -std=c++17 ...
| Name | Type / Signature | Description |
|---|---|---|
| std::exception | base class | Root of all standard exceptions; has what() |
| std::runtime_error | : exception | Error detected at runtime |
| std::logic_error | : exception | Logic bug in the program |
| std::invalid_argument | : logic_error | Invalid argument passed to a function |
| std::out_of_range | : logic_error | Access beyond valid range |
| std::overflow_error | :runtime_error | Arithmetic overflow |
| std::bad_alloc | : exception | Thrown by new when allocation fails |
| std::bad_cast | : exception | Thrown by dynamic_cast on invalid cast |
| e.what() | const char * | Return description of the exception |
| throw expr | statement | Throw an exception object |
| try { } catch(T &e) {} | statement | Catch block — use const reference |
| catch(...) {} | statement | Catch any exception (use as last resort) |
Copy, save as demo.cpp, and compile with the command at the bottom.
#include <iostream>
#include <stdexcept>
#include <vector>
using namespace std;
double safe_divide(double a, double b) {
if (b == 0.0) throw invalid_argument("Division by zero");
return a / b;
}
int main() {
try {
cout << safe_divide(10.0, 2.0) << "\n";
cout << safe_divide(10.0, 0.0) << "\n"; // throws
}
catch (const invalid_argument &e) {
cerr << "Invalid argument: " << e.what() << "\n";
}
try {
vector<int> v = {1, 2, 3};
cout << v.at(10) << "\n"; // throws out_of_range
}
catch (const out_of_range &e) {
cerr << "Out of range: " << e.what() << "\n";
}
try { throw runtime_error("Something went wrong"); }
catch (const exception &e) {
cerr << "Caught: " << e.what() << "\n";
}
cout << "Program continues after exceptions.\n";
return 0;
}
// Compile: g++ -Wall -std=c++17 -o except_demo except_demo.cpp