std::exception_ptr


Type: 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.

Key Concepts

Example Scenario: Capturing and Rethrowing Exceptions Across Threads

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;
}

Explanation

Output

Caught exception: Something went wrong in the thread!

When to Use std::exception_ptr

Benefits of std::exception_ptr

Conclusion

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.

Previous Page | Course Schedule | Course Content