C++ Throwing an Exception from a Function

In C++, exceptions can be used to signal errors or unexpected conditions that occur during program execution. When an error occurs in a function, the function can throw an exception to indicate that an error has occurred. Here is an example of how to throw an exception from a function:

int divide(int a, int b) {
    if (b == 0) {
        throw std::invalid_argument("divide by zero");
    }
    return a / b;
}
Source‮:‬www.theitroad.com

In this example, the divide function takes two integer arguments and returns the result of dividing the first argument by the second argument. If the second argument is zero, the function throws an exception of type std::invalid_argument with the message "divide by zero".

To throw an exception from a function, you simply use the throw keyword followed by an expression that evaluates to an object of an exception type. In this example, the std::invalid_argument exception is constructed with a string message and thrown using the throw keyword.

When an exception is thrown, it interrupts the normal flow of the program and starts a process of searching for a catch block that can handle the exception. If no matching catch block is found, the program will terminate with an error.

To catch an exception thrown by a function, you can use a try-catch block, like this:

try {
    int result = divide(10, 0);
}
catch (const std::exception& e) {
    std::cerr << "Exception caught: " << e.what() << std::endl;
}

In this example, the divide function is called with arguments 10 and 0, which causes it to throw an exception. The try-catch block catches the exception and prints an error message to the standard error stream.

In summary, throwing an exception from a function in C++ is a powerful way to handle errors and unexpected conditions in your program. When you throw an exception, you can provide information about the error that occurred, and when you catch an exception, you can take appropriate action to handle the error and continue with the normal flow of your program.