C++ - Exceptions Handling

In C++, exceptions are a powerful mechanism for handling exceptional conditions or errors that occur during the execution of a program. The try and catch blocks are used to handle exceptions in C++.

The try block is used to enclose the code that may throw an exception. If an exception is thrown within the try block, the execution of the try block is immediately halted, and the control is transferred to the nearest matching catch block.

The catch block is used to catch and handle exceptions. It specifies the type of exception it can catch, and if an exception of that type is thrown, the code within the corresponding catch block is executed.

#include <iostream>
int main() {
    try {
        // Code that may throw an exception
        int num1, num2;
        std::cout << "Enter two numbers: ";
        std::cin >> num1 >> num2;
        if (num2 == 0) {
            throw "Division by zero error";  // Throwing an exception
        }
        int result = num1 / num2;
        std::cout << "Result: " << result << std::endl;
    }
    catch (const char* errorMessage) {
        // Catching and handling the exception
        std::cout << "Exception caught: " << errorMessage << std::endl;
    }
    return 0;
}

In this example, we prompt the user to enter two numbers and perform division. If the second number is zero, we intentionally throw an exception using the throw statement, indicating a division by zero error.

The catch block catches the exception of type const char* (pointer to a character array), which matches the type of the thrown exception. Inside the catch block, we handle the exception by displaying an error message.

By running the program, if the user enters a second number as zero, the exception is thrown, and the program flow is transferred to the catch block. The error message is displayed, indicating the division by zero error.

Additionally, in C++, you can handle any type of exception using the ellipsis (...) in the catch block. This allows you to catch and handle any exception thrown within the try block, regardless of its type. However, it's generally recommended to catch specific types of exceptions to provide more targeted and meaningful error handling.

try {
    // Code that may throw an exception
}
catch (...) {
    // Catching and handling any type of exception
}

In this case, the catch block with ellipsis can catch exceptions of any type, but it doesn't provide specific information about the exception type. Therefore, it's important to use it with caution and consider more specific exception handling approaches whenever possible.