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:
std::exception_ptr
using std::current_exception()
.std::exception_ptr
to the thread where you want to handle the exception.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.
This lesson offers a comprehensive guide to storing and rethrowing exceptions