Custom Exception Types in C++
Standard exceptions cover generic failures, but domain errors deserve domain types: class ConfigError : public std::runtime_error adds a catchable category callers can handle precisely while keeping what() messaging free through the base constructor. Deriving from std::exception (usually via runtime_error or logic_error) plugs into every existing catch (const std::exception&) handler automatically.
Enrich with context members (filename, line, error code) set at throw time, keep them copyable (handlers may copy), and never let destructors throw. One well-placed custom hierarchy beats a dozen stringly-typed runtime_errors.
Derive from runtime_error
class ConfigError : public std::runtime_error { public: using std::runtime_error::runtime_error; }; — inherits constructors and what() in two lines.
Catch precisely
catch (const ConfigError& e) handles config failures specifically while other runtime_errors fall through to broader handlers.
Carry context
Add filename/line/code members initialized at throw — debugging from what() plus structured fields beats bare messages.
Keep them copy-safe
Exception objects get copied during unwinding — value members only, no raw owning pointers, destructors that never throw.
#include <iostream>#include <stdexcept>#include <string> class ConfigError : public std::runtime_error {public: using std::runtime_error::runtime_error;}; int main() { try { throw ConfigError("missing key: timeout"); } catch (const ConfigError& e) { std::cout << "config: " << 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.