example1_capturing_rethrowing.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#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;
}
Back to std_exception_ptr