Nested Exceptions

Handling Nested Exceptions with Multiple Catch Blocks

Can I handle nested exceptions using multiple catch blocks? If so, in what order are they caught?

Abstract art representing computer programming

Yes, you can use multiple catch blocks to handle nested exceptions. The catch blocks will be tried in order, and the first one that matches the exception type will be executed.

For example:

try {
  try {
    throw std::runtime_error{"Inner Exception"};
  } catch (...) {
    std::throw_with_nested(
      std::logic_error{"Outer Exception"});
  }
} catch (std::logic_error& e) {
  std::cout << "Caught logic_error: "
    << e.what() << '\n';
  // Rethrow the std::runtime_error if desired
  // std::rethrow_if_nested(e);
}
Caught logic_error: Outer Exception

In this example, the std::logic_error is caught first because it's the type we directly threw. When we call std::rethrow_if_nested(e), it then throws the nested std::runtime_error, which is caught by the next matching catch block.

This Question is from the Lesson:

Nested Exceptions

Learn about nested exceptions in C++: from basic concepts to advanced handling techniques

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

This Question is from the Lesson:

Nested Exceptions

Learn about nested exceptions in C++: from basic concepts to advanced handling techniques

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