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

Custom Exception Types in C++

//concept

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.

//how it works
1

Derive from runtime_error

class ConfigError : public std::runtime_error { public: using std::runtime_error::runtime_error; }; — inherits constructors and what() in two lines.

2

Catch precisely

catch (const ConfigError& e) handles config failures specifically while other runtime_errors fall through to broader handlers.

3

Carry context

Add filename/line/code members initialized at throw — debugging from what() plus structured fields beats bare messages.

4

Keep them copy-safe

Exception objects get copied during unwinding — value members only, no raw owning pointers, destructors that never throw.

//example
#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;
}
Output
config: missing key: timeout
1ConfigError inherits runtime_error's constructors, so it throws with a message and answers what().
2The first handler matches the derived type exactly and reports it as a config problem.
3The generic std::exception handler below never fires — precise catch first, general catch as backstop.
//use cases
Domain error vocabularies (ParseError, AuthError, TimeoutError) callers handle distinctly
Library APIs whose failures users catch without parsing message strings
Enriching errors with file/line/code context at the throw site
Keeping catch (const std::exception&) as the universal safety net

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.