Nested Exceptions

Propagating Nested Exceptions Across Threads

Can I throw a nested exception from one thread and catch it in another thread?

Abstract art representing computer programming

Yes, you can propagate nested exceptions across threads, with some caveats.

In C++11 and later, if a function called by std::thread exits with an uncaught exception, the runtime captures that exception and stores it. When you call join() or get() on the std::thread or std::future object, it will rethrow that stored exception.

This works with nested exceptions too. If the thread function exits with an uncaught nested exception, it will be captured and rethrown when join() or get() is called.

For example:

#include <exception>
#include <iostream>
#include <thread>

void thread_func() {
  try {
    throw std::runtime_error{"Inner Exception"};
  } catch (...) {
    std::throw_with_nested(
      std::logic_error{"Outer Exception"});
  }
}

void join_thread() {
  try {
    std::thread t{thread_func};
    t.join();
  } catch (const std::exception& e) {
    std::cout << "Caught exception: " << e.what() << '\n';
    // Rethrow the std::runtime_error if desired
    // std::rethrow_if_nested(e);
  }
}

However, there are some limitations:

  1. The exception types must be copyable, because the exception is copied into the std::thread or std::future object.
  2. If the thread function exits via other means (e.g., by calling std::terminate), the behavior is undefined.
  3. If the std::thread or std::future object is destroyed without calling join() or get(), the stored exception is lost and std::terminate is called.

So while you can propagate nested exceptions across threads, it's important to handle and rethrow them properly to avoid unexpected behavior.

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