Capturing Thread Exceptions in C++

When a thread in C++ or in almost any other language runs the execution happens in a different execution path to the main thread that runs. This means that unless you explicitly have a mechanism for returning data or exceptions back to the caller you will not be able to send anything back to your parent that called you. In C++ there is the



static std::exception_ptr globalExceptionPtr = nullptr;



the std::exception_ptr will catch and hold any exception that gets thrown. Here it is a global, and we should try to never use them but how do you sensibly return exceptions from threads ?

Here is some code that uses the above concept. Where do you think the exception is caught? It would be fair game to assume it is in the catch surrounding the thread call. However this is not the case as its in a different thread of execution. Instead you must check the globalExceptionPtr




static std::exception_ptr globalExceptionPtr = nullptr;

void exceptionThrowingFunc()
{
try
{
std::this_thread::sleep_for(std::chrono::milliseconds(100));
throw std::runtime_error("exceptionThrowingFunc Threw an Exception");
}
catch (...)
{
//Set the global exception pointer in case of an exception
globalExceptionPtr = std::current_exception();
}
}

int main()
{


try {
std::thread t1(exceptionThrowingFunc);
t1.
join();
}
catch (const std::exception &ex) {
//Does this catch thread exceptions ??
std::cout << "Thread had an Exception" << std::endl;
}



if (globalExceptionPtr)
{
try
{
std::rethrow_exception(globalExceptionPtr);
}
catch (const std::exception &ex)
{
std::cout << "Caught via std::exception_ptr " << ex.what() << "\n";
}
}
return 0;
}




It would be great if there was a more OO or functional way of returning exceptions from threads however if you know of a better way then please let me know.
Please note Future and Promise actually allow you to set_exception() on themselves and then when get() is called they re throw that exception which is why they are preferred to normal raw Asynch thread calls.



People who enjoyed this article also enjoyed the following:


C++ Asynch future promise package_task and shared_future
Blocking Queue in C++ using condition variable
Creating C++ threads
Low Latency Java using CAS and LongAdder
Naive Bayes classification AI algorithm
K-Means Clustering AI algorithm
Equity Derivatives tutorial
Fixed Income tutorial


And the following Trails:

C++
Java
python
Scala
Investment Banking tutorials

HOME
homeicon



By clicking Dismiss you accept that you may get a cookie that is used to improve your user experience and for analytics.
All data is anonymised. Our privacy page is here =>
Privacy Policy
This message is required under GDPR (General Data Protection Rules ) and the ICO (Information Commissioners Office).