The Standard Exception Hierarchy in C++
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.
One root, two branches
Everything derives from std::exception::what(); logic_error means caller bugs, runtime_error means world failures.
Know the regulars
out_of_range (at(), substr), invalid_argument (stoi), bad_alloc (exhausted memory), bad_cast/bad_function_call (misused wrappers).
Catch narrow, backstop wide
Handle recoverable specifics first, end with catch (const std::exception&) logging what() for everything unforeseen.
Extend, don't fork
Custom errors derive from runtime_error or logic_error β they stay catchable by existing generic handlers.
#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;}Recommended resourcesAffiliate links Β· may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself β building beats watching.