C++20 sections · 1024 units
Open in Course

Inheriting from std::exception

Proper exception derivation

To create custom exception types, inherit from std::exception or a subclass and override what().

Example: class FileError : public runtime_error { public: FileError(const string& msg) : runtime_error(msg) {} };

Your custom exception can carry extra data: class NetworkError : public runtime_error { public: int errorCode; NetworkError(int code, const string& msg) : runtime_error(msg), errorCode(code) {} };

Callers can catch your specific type: catch (const FileError& e) { /* handle file errors */ } or catch broadly with runtime_error or exception.