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.
Answers to questions are automatically generated and may not have been reviewed.
Gain a thorough understanding of exception types, including how to throw and catch both standard library and custom exceptions in your code