Custom Exceptions
Creating your own exception classes
Interview Relevant: Exception design
Custom Exceptions
Define domain-specific exception types.
Code Examples
Creating custom exception classes.
cpp
1class NetworkException : public runtime_error {
2public:
3 NetworkException(const string& msg) : runtime_error(msg) {}
4};
5
6class ConnectionTimeoutException : public NetworkException {
7 int timeoutMs;
8public:
9 ConnectionTimeoutException(int ms)
10 : NetworkException("Connection timed out after " + to_string(ms) + "ms"),
11 timeoutMs(ms) {}
12
13 int getTimeout() const { return timeoutMs; }
14};
15
16// Exception with error code
17class FileException : public exception {
18 string message;
19 int errorCode;
20public:
21 FileException(const string& msg, int code)
22 : message(msg), errorCode(code) {}
23
24 const char* what() const noexcept override {
25 return message.c_str();
26 }
27
28 int getErrorCode() const { return errorCode; }
29};
30
31try {
32 throw ConnectionTimeoutException(5000);
33} catch (const ConnectionTimeoutException& e) {
34 cout << e.what() << " (timeout: " << e.getTimeout() << "ms)" << endl;
35}