c++ - Exception not caught if raised after spawning std::thread -
i'm puzzled strange behavior of exceptions, thrown in main thread after spawning thread:
void thread_body(){ while(true) cout << "in thread" << endl; } int main(int argc, char** argv) { try{ auto t = std::thread( thread_body ); throw std::runtime_error("error!"); t.join(); } catch (const std::exception& e) { cout << e.what() << endl; } }
the output is:
in thread in thread in thread terminate called without active exception program has unexpectedly finished.
if throw before spawning thread this:
throw std::runtime_error("error!"); auto t = std::thread( thread_body );
than caught normally:
error!
why exception not caught in first case? should catch in usual way?
when exception thrown thread object destroyed. thread destructor called while still joinable. causes terminate
called exception handler never invoked.
also writing standard streams different threads without proper synchronization not idea.
Comments
Post a Comment