C++ try catch

In C++, the try-catch block is used for exception handling. It allows you to catch and handle exceptions that may occur during the execution of a specific code segment. The try block contains the code that might throw an exception, and the catch block handles the exception if it is thrown.

The general syntax of the try-catch block in C++ is as follows:

Example
try {
    // Code that may throw an exception
} catch (ExceptionType1 exception1) {
    // Handle exception1
} catch (ExceptionType2 exception2) {
    // Handle exception2
} catch (...) {
    // Handle any other type of exception
}

Here's an example to illustrate the usage of try-catch block in C++:

Example
#include 

int divide(int numerator, int denominator) {
    if (denominator == 0) {
        throw "Division by zero error";  // Throwing an exception
    }
    return numerator / denominator;
}

int main() {
    int a = 10;
    int b = 0;

    try {
        int result = divide(a, b);  // Potential exception-causing code
        std::cout << "Result: " << result << std::endl;
    } catch (const char* error) {
        std::cerr << "Exception caught: " << error << std::endl;
    }

    return 0;
}

In the example above, the divide() function performs division between two integers. If the denominator is zero, it throws an exception using the throw statement. The main() function calls divide() within a try block. If an exception is thrown, the corresponding catch block catches the exception and displays an error message.

In the catch block, you specify the type of exception you want to catch. You can have multiple catch blocks to handle different types of exceptions. If an exception matches the specified type, the corresponding catch block is executed. If none of the specified exception types match, the last catch block with ellipsis (...) can catch any other type of exception.

It's important to note that the catch blocks are checked in order, from top to bottom, so it's recommended to have more specific exception types before more general ones.

By using the try-catch block, you can effectively handle exceptions and take appropriate actions, such as displaying error messages, performing cleanup operations, or gracefully terminating the program when an exceptional condition occurs. Exception handling allows you to control the flow of your program and ensure it handles errors gracefully.