Standard Exceptions
std::exception hierarchy
Interview Relevant: Built-in exceptions
Standard Exceptions
The standard exception class hierarchy.
Code Examples
Standard exception types and hierarchy.
cpp
1// Exception hierarchy
2// exception (base)
3// ├── logic_error
4// │ ├── invalid_argument
5// │ ├── domain_error
6// │ ├── length_error
7// │ └── out_of_range
8// ├── runtime_error
9// │ ├── range_error
10// │ ├── overflow_error
11// │ └── underflow_error
12// └── bad_alloc, bad_cast, etc.
13
14#include <stdexcept>
15
16void validate(const string& str) {
17 if (str.empty()) {
18 throw invalid_argument("String cannot be empty");
19 }
20}
21
22int getElement(const vector<int>& v, size_t index) {
23 if (index >= v.size()) {
24 throw out_of_range("Index " + to_string(index) + " out of range");
25 }
26 return v[index];
27}
28
29// All standard exceptions have what()
30try {
31 throw runtime_error("Something went wrong");
32} catch (const exception& e) {
33 cout << e.what() << endl; // "Something went wrong"
34}