Reputation: 1281
//...
try
{
std::thread someThread(someFunc, someArg); // assume it doesn't throw
foo(); // might throw
bar(); // might throw
someThread.join();
}
//...
In the above example, if either foo()
or bar()
throws, someThread
's destructor will call the terminate()
function because someThread
had not been joined to the parent thread due to stack unwinding, that will lead to termination of the entire program. Is there any way to prevent this behavior and handle the exception without killing the program?
Upvotes: 1
Views: 203
Reputation: 12899
One option would be to simply declare someThread
before the try/catch block and use move-assignment in the try
clause. Then call to join
can then be immediately after the catch
clause...
std::thread someThread;
try
{
someThread = std::thread(someFunc, someArg);
foo(); // might throw
bar(); // might throw
}
catch (...) {
/*
* Do some error handling...
*/
}
if (someThread.joinable())
someThread.join();
Alternatively, if your compiler supports c++20
youmight want to look at std::jthread
.
Upvotes: 2