Storing and Rethrowing Exceptions

Handling Nested Exceptions

What is a good strategy for handling exceptions that are thrown while already handling another exception?

Abstract art representing computer programming

When an exception is thrown while already handling another exception, it's called a nested exception. This can lead to tricky situations and potential resource leaks if not handled carefully.

One strategy is to catch and handle the nested exception separately, and then continue handling the original exception:

#include <iostream>
#include <stdexcept>

void handleException() {
  try {
    throw std::runtime_error(
      "Original exception");
  } catch (const std::exception& e) {
    std::cout << "Handling: "
      << e.what() << "\n";
    try {
      throw std::logic_error("Nested exception");
    } catch (const std::exception& nested_e) {
      std::cout << "Handling nested: "
        << nested_e.what() << "\n";
    }
    std::cout << "Continuing handling "
      "original exception\n";
  }
}

int main() {
  handleException();
}
Handling: Original exception
Handling nested: Nested exception
Continuing handling original exception

Another approach is to capture the nested exception using std::current_exception(), store it in a std::exception_ptr, and then rethrow it after finishing handling the original exception:

#include <exception>
#include <iostream>
#include <stdexcept>

void handleException() {
  std::exception_ptr nested_eptr;
  try {
    throw std::runtime_error(
      "Original exception");
  } catch (const std::exception& e) {
    std::cout << "Handling: " << e.what() << "\n";
    try {
      throw std::logic_error("Nested exception");
    } catch (...) {
      nested_eptr = std::current_exception();
    }
    std::cout << "Continuing handling "
      "original exception\n";
  }
  if (nested_eptr) {
    std::rethrow_exception(nested_eptr);
  }
}

int main() {
  try {
    handleException();
  } catch (const std::exception& e) {
    std::cout << "Caught rethrown nested "
      "exception: " << e.what() << "\n";
  }
}
Handling: Original exception
Continuing handling original exception
Caught rethrown nested exception: Nested exception

This ensures the nested exception isn't lost and can be handled at a higher level if needed.

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

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