Handling Multiple Exception Types in a Single Catch Block

Is it possible to catch and handle multiple exception types in a single catch block?

Yes, it is possible to catch and handle multiple exception types in a single catch block using the std::exception base class. First, declare a catch block that catches exceptions of type std::exception&:

try {
  // Code that may throw exceptions
} catch (const std::exception& e) {
  // Handle the exception
}

Inside the catch block, you can use the dynamic_cast operator to determine the specific type of exception that was caught:

try {
  // Code that may throw exceptions
} catch (const std::exception& e) {
  if (dynamic_cast<const TypeA*>(&e)) {
    // Handle exceptions of type TypeA
  } else if (dynamic_cast<const TypeB*>(&e)) {
    // Handle exceptions of type TypeB
  } else {
    // Handle other std::exception-derived types
  }
}

Alternatively, you can use the typeid operator to get information about the caught exception type:

try {
  // Code that may throw exceptions
} catch (const std::exception& e) {
  if (typeid(e) == typeid(TypeA)) {
    // Handle TypeA
  } else if (typeid(e) == typeid(TypeB)) {
    // Handle TypeB
  } else {
    // Handle other std::exception-derived types
  }
}

By catching the base std::exception class, you can handle multiple exception types derived from std::exception in a single catch block. This allows you to centralize the exception handling logic and perform specific actions based on the actual exception type.

However, keep in mind that catching exceptions by reference to the base class may limit your ability to access exception-specific data or functions. If you need to access such data or functions, you may need to catch the specific exception types individually.

Exception Types

Gain a thorough understanding of exception types, including how to throw and catch both standard library and custom exceptions in your code

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Customizing Error Messages in Custom Exception Types
How can I provide custom error messages when throwing my own exception types?
Performance Impact of Exception Handling
Does using exception handling have a significant impact on program performance?
Best Practices for Exception Handling in C++
What are some best practices to follow when using exception handling in C++?
Understanding Exception Specifications in C++
What are exception specifications in C++ and when should they be used?
Handling Exceptions in Constructors
How should exceptions be handled when thrown from constructors in C++?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant