std::exception_ptr
in C++The std::exception_ptr
is a powerful tool introduced in C++11 that allows you to capture and store exceptions, and then rethrow them later, potentially in a different context, such as another thread or function. It is especially useful in asynchronous programming, where exceptions need to be propagated between different parts of the code, for instance, from a worker thread back to the main thread.
std::current_exception()
which returns a std::exception_ptr
to the current exception.std::exception_ptr
can store any type of exception and can be safely passed around or stored.std::rethrow_exception()
.Here's an example where we capture an exception in one thread, store it using std::exception_ptr
, and then rethrow it in the main thread.
#include <iostream>
#include <thread>
#include <exception>
std::exception_ptr globalExceptionPtr = nullptr;
void faultyFunction() {
try {
// Simulate an exception being thrown
throw std::runtime_error("Something went wrong in the thread!");
} catch (...) {
// Capture the exception and store it in the global exception pointer
globalExceptionPtr = std::current_exception();
}
}
int main() {
// Start a thread that may throw an exception
std::thread t(faultyFunction);
t.join();
// Check if an exception was captured
if (globalExceptionPtr) {
try {
// Rethrow the exception in the main thread
std::rethrow_exception(globalExceptionPtr);
} catch (const std::exception& e) {
// Handle the exception here
std::cerr << "Caught exception: " << e.what() << std::endl;
}
} else {
std::cout << "No exception caught in the thread." << std::endl;
}
return 0;
}
std::exception_ptr globalExceptionPtr = nullptr;
: We declare a global std::exception_ptr
to store the exception that might be thrown in the thread.try-catch
block in faultyFunction()
: Within the thread, an exception is thrown and immediately caught. The std::current_exception()
function is used to capture the current exception and store it in the globalExceptionPtr
.std::rethrow_exception(globalExceptionPtr);
: In the main thread, after the worker thread has completed, we check if an exception was captured. If so, we rethrow it using std::rethrow_exception()
and handle it in the main thread’s catch
block.Caught exception: Something went wrong in the thread!
std::exception_ptr
std::exception_ptr
std::exception_ptr
is type-safe and can store any type of exception.std::exception_ptr
is a versatile tool in modern C++ that enhances the robustness of exception handling, especially in multithreaded or asynchronous applications. It allows developers to safely capture, store, and rethrow exceptions across different contexts, ensuring that exceptions are handled appropriately no matter where they occur.