Exception Types

Handling Multiple Exception Types in a Single Catch Block

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

Abstract art representing computer programming

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.

This Question is from the Lesson:

Exception Types

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

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

Exception Types

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

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved