Storing and Rethrowing Exceptions

Capturing Exceptions in a Different Thread

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

Abstract art representing computer programming

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.

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:

  • 125 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