example2_throwing_custom_exceptions.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
#include <iostream>
#include <string>

class NetworkError : public std::exception {
private:
    std::string message;
public:
    NetworkError(const std::string& msg) : message(msg) {}
    const char* what() const noexcept override {
        return message.c_str();
    }
};


void connectToServer(const std::string& server) {
    if (server.empty()) {
        throw NetworkError("Empty server address");
    }
    if (server == "localhost") {
        throw NetworkError("Cannot connect to localhost");
    }
    std::cout << "Connected to " << server << std::endl;
}

int main() {
    try {
        connectToServer("example.com");
        connectToServer("localhost");
    } catch (const NetworkError& e) {
        std::cerr << "Network error: " << e.what() << std::endl;
    }
    return 0;
}
Back to throw