Learn C++
#include "exceptionhandling/std_exceptions.hpp"

The Standard Exception Hierarchy in C++

//concept

The standard library throws from a rooted family: std::exception at the top (with what()), splitting into logic_error (preventable bugs: out_of_range, invalid_argument, length_error) and runtime_error (environmental failures: overflow, underflow, system_error). Containers, strings, and streams throw these instead of inventing their own β€” at() throws out_of_range, stoi throws invalid_argument.

Catch strategy follows the tree: specific types where you can recover (retry on system_error, clamp on out_of_range), const std::exception& as the universal backstop. Custom project errors should join the family by deriving from the nearest standard cousin.

//how it works
1

One root, two branches

Everything derives from std::exception::what(); logic_error means caller bugs, runtime_error means world failures.

2

Know the regulars

out_of_range (at(), substr), invalid_argument (stoi), bad_alloc (exhausted memory), bad_cast/bad_function_call (misused wrappers).

3

Catch narrow, backstop wide

Handle recoverable specifics first, end with catch (const std::exception&) logging what() for everything unforeseen.

4

Extend, don't fork

Custom errors derive from runtime_error or logic_error β€” they stay catchable by existing generic handlers.

//example
#include <iostream>
#include <vector>
#include <stdexcept>
Β 
int main() {
std::vector<int> v{1, 2};
try {
std::cout << v.at(9) << std::endl;
} catch (const std::out_of_range& e) {
std::cout << "range: " << e.what() << std::endl;
} catch (const std::exception& e) {
std::cout << "other: " << e.what() << std::endl;
}
return 0;
}
Output
range: vector
1at(9) bounds-checks and throws out_of_range instead of reading garbage like operator[] would.
2The specific handler matches first and reports it as a range problem with the library's message.
3The generic backstop never fires β€” narrow catches precede wide ones by design.
//use cases
Bounds-checked access with at() plus out_of_range recovery
Parsing with stoi guarded by invalid_argument/out_of_range handlers
Generic logging backstops via const std::exception& and what()
Placing custom errors inside the standard family tree

Recommended resourcesAffiliate links Β· may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice β€” pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from β€” great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself β€” building beats watching.