Capturing Exceptions in a Different Thread

How can I capture an exception thrown in one thread and handle it in a different thread?

One way to capture an exception in one thread and handle it in another is to use std::exception_ptr in combination with std::current_exception() and std::rethrow_exception():

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

std::exception_ptr captureException() {
  try {
    throw std::runtime_error("Error in thread");
  } catch(...) {
    return std::current_exception();
  }
}

void handleException(std::exception_ptr eptr) {
  try {
    if (eptr) {
      std::rethrow_exception(eptr);
    }
  } catch(const std::exception& e) {
    std::cout << "Caught exception: "
      << e.what() << "\n";
  }
}

int main() {
  std::exception_ptr eptr;
  std::thread t([&]{
    eptr = captureException();
  });
  t.join();
  handleException(eptr);
}
Caught exception: Error in thread

The key steps are:

  1. In the thread where the exception occurs, catch the exception and capture it into a std::exception_ptr using std::current_exception().
  2. Transfer this std::exception_ptr to the thread where you want to handle the exception.
  3. In the handling thread, use std::rethrow_exception() to rethrow the original exception, which can then be caught and handled as usual.

This allows exceptions to cross thread boundaries while preserving their type information.

Storing and Rethrowing Exceptions

This lesson offers a comprehensive guide to storing and rethrowing exceptions

Questions & Answers

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

Handling Nested Exceptions
What is a good strategy for handling exceptions that are thrown while already handling another exception?
Rethrowing Exceptions and noexcept
What happens if I rethrow an exception in a noexcept function?
Using std::exception_ptr Across DLL Boundaries
Can I use std::exception_ptr to transfer exceptions across DLL boundaries?
Capturing and Rethrowing Custom Exceptions
Can I use std::exception_ptr to capture and rethrow custom exceptions?
std::exception_ptr and Memory Management
Are there any memory management considerations when using std::exception_ptr?
Performance Considerations with std::exception_ptr
What are the performance implications of using std::exception_ptr?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant