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

class CustomException : public std::exception {
private:
    std::string message;

public:
    explicit CustomException(const std::string& msg) : message(msg) {}

    const char* what() const noexcept override {
        return message.c_str();
    }
};

void riskyFunction(int value) {
    if (value < 0) {
        throw CustomException("Negative value not allowed");
    }
    std::cout << "Processing value: " << value << std::endl;
}

int main() {
    try {
        riskyFunction(5);
        riskyFunction(-1);
    } catch (const CustomException& e) {
        std::cerr << "Custom exception caught: " << e.what() << std::endl;
    } catch (const std::exception& e) {
        std::cerr << "Standard exception caught: " << e.what() << std::endl;
    }

    return 0;
}
Back to exception