Search code examples
c++multithreadingexceptionstdthread

Exception not caught if raised after spawning std::thread


I'm puzzled by the strange behavior of exceptions, which are thrown in main thread after spawning another 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 an active exception
The program has unexpectedly finished.

If I throw before spawning the thread like this:

throw std::runtime_error("error!");
auto t = std::thread( thread_body );

than it is caught normally:

error!

Why exception is not caught in first case? What should I do to catch it in usual way?


Solution

  • When exception is thrown thread object will be destroyed. But thread destructor will be called while it is still joinable. This causes terminate to be called so exception handler is never invoked.

    Also writing into standard streams from different threads without proper synchronization is not a good idea.