I was expecting that the status of sub-thread, whether they succeed or not, should not crash main thread.
So I had a quick test:
#include <thread>
#include <iostream>
#include <exception>
using namespace std;
using namespace std::chrono;
void th_function() {
this_thread::sleep_for(chrono::seconds(2));
throw 1; // the criminal here!
}
int main() {
auto th = thread{ th_function };
this_thread::sleep_for(chrono::seconds(1));
cout << "1" << endl;
th.join();
cout << "2" << endl;
return 0;
}
The running result is:
1
Program stderr
terminate called after throwing an instance of 'int'
Well, seems the throw 1
call leads to main thread crash. I think for c , each thread has its own runtime stack and exception-process chain.
Then why in my case, sub-thread exception will terminate main thread?
Thanks.
CodePudding user response:
It is true that exceptions handling is localized to a single thread, but as always, not catching an exception at all causes a call to std::terminate
, which in turn terminates the whole program. The same applies to other conditions resulting in a call to std::terminate
, e.g. throwing from a destructor during stack unwinding or letting an exception escape a noexcept
function. These are all considered unrecoverable errors.
You can use e.g. std::async
if you need to continue execution after an unhandled exception in the thread. std::async
includes functionality to catch otherwise uncaught exceptions and stores/forwards them in a std::future
, so that the main thread can receive them.