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