Example: Throw new Exception

Here’s an example of how to use throw with built-in and custom exception types:

#include <iostream>
#include <stdexcept>  // For standard exceptions

// Custom exception class
class MyCustomException : public std::exception {
public:
    const char* what() const noexcept override {
        return "A custom exception occurred!";
    }
};

int main() {
    try {
        // Throw an integer as an exception
        throw 42;
    } 
    catch (int e) {
        std::cout << "Caught an integer exception: " << e << '\n';
    }

    try {
        // Throw a standard exception
        throw std::runtime_error("Runtime error occurred!");
    }
    catch (const std::runtime_error& e) {
        std::cout << "Caught a runtime error: " << e.what() << '\n';
    }

    try {
        // Throw a custom exception
        throw MyCustomException();
    }
    catch (const MyCustomException& e) {
        std::cout << "Caught a custom exception: " << e.what() << '\n';
    }

    return 0;
}

Key Points

Throwing custom exceptions: The third throw throws a custom exception class (MyCustomException). The what() method provides an error message, which can be accessed using e.what() in the catch block.

Throwing built-in types: In the first throw, an integer (42) is thrown and caught by a catch (int) block.

Throwing standard exceptions: In the second throw, a std::runtime_error is thrown, and the catch block catches it by reference.