example2_custom_exception.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
#include <stdexcept>
#include <string>

class NetworkError : public std::runtime_error {
public:
    NetworkError(const std::string& message) 
        : std::runtime_error(message), errorCode(0) {}
    NetworkError(const std::string& message, int code) 
        : std::runtime_error(message), errorCode(code) {}

    int getErrorCode() const { return errorCode; }

private:
    int errorCode;
};

void connectToServer(const std::string& server) {
    if (server.empty()) {
        throw NetworkError("Empty server address", 404);
    }
    // Simulating a connection error
    throw NetworkError("Failed to connect to server: " + server, 500);
}

int main() {
    try {
        connectToServer("example.com");
    }
    catch (const NetworkError& e) {
        std::cerr << "Network error: " << e.what() 
                  << " (Error code: " << e.getErrorCode() << ")" << std::endl;
    }
    catch (const std::exception& e) {
        std::cerr << "Standard exception: " << e.what() << std::endl;
    }

    return 0;
}
Back to std_runtime_error