C++ Handling Multiple Exceptions

ht‮pt‬s://www.theitroad.com

In C++, it is common to encounter situations where a function can throw multiple types of exceptions. In such cases, you may want to catch and handle each exception type differently. Here's an example of how to handle multiple exceptions in C++:

try {
    // code that may throw exceptions
}
catch (const std::exception& e) {
    std::cerr << "Exception caught: " << e.what() << std::endl;
}
catch (const std::string& s) {
    std::cerr << "String exception caught: " << s << std::endl;
}
catch (...) {
    std::cerr << "Unknown exception caught" << std::endl;
}

In this example, the try block contains code that may throw exceptions of different types. The first catch block catches exceptions of type std::exception and its subclasses, such as std::invalid_argument and std::runtime_error. The second catch block catches exceptions of type std::string. The third catch block catches any other exception that is not caught by the first two catch blocks.

It's important to note that the catch blocks are evaluated in order, from top to bottom. If an exception of type std::exception is thrown, the first catch block will be executed, and the second and third catch blocks will be skipped. If an exception of type std::string is thrown, the first catch block will be skipped, and the second catch block will be executed.

It's also possible to catch multiple exception types in a single catch block, using the | operator to separate the exception types. For example:

try {
    // code that may throw exceptions
}
catch (const std::invalid_argument& | const std::out_of_range& e) {
    std::cerr << "Invalid argument or out of range exception caught: " << e.what() << std::endl;
}
catch (...) {
    std::cerr << "Unknown exception caught" << std::endl;
}

In this example, the first catch block catches exceptions of type std::invalid_argument and std::out_of_range using the | operator. If an exception of either type is thrown, the first catch block will be executed.

In summary, handling multiple exceptions in C++ is a powerful way to handle errors and unexpected conditions in your program. You can catch and handle each exception type differently, or catch multiple exception types in a single catch block using the | operator.