Propagating Nested Exceptions Across Threads

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

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.

Nested Exceptions

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

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Throwing Non-Exceptions with std::throw_with_nested()
What happens if I pass a non-exception type to std::throw_with_nested()?
Handling Nested Exceptions with Multiple Catch Blocks
Can I handle nested exceptions using multiple catch blocks? If so, in what order are they caught?
Performance Impact of Nested Exceptions
Is there a performance penalty when using nested exceptions compared to regular exceptions?
Throwing Nested Exceptions from Destructors
Is it safe to throw nested exceptions from a destructor?
Propagating Nested Exceptions Across DLL Boundaries
Can I throw a nested exception from a function in a DLL and catch it in the calling code?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant