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:
- In the thread where the exception occurs, catch the exception and capture it into a
std::exception_ptr
usingstd::current_exception()
. - Transfer this
std::exception_ptr
to the thread where you want to handle the exception. - 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