Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ exception not being handled in thread

Why is no unhandled exception exception given by VS 2013, or any abort signal raised when the following code is executed?

#include <thread>

void f1()
{
    throw(1);
}

int main(int argc, char* argv[])
{
    std::thread(f1);
}

The C++ standard states that std::terminate should be called in the following situation:

when the exception handling mechanism cannot find a handler for a thrown exception (15.5.1)

in such cases, std::terminate() is called (15.5.2)

like image 203
developerbmw Avatar asked Jul 19 '14 08:07

developerbmw


1 Answers

The problem is that in this code, main() could end before the spawned thread (f1).

Try this instead:

#include <thread>

void f1()
{
    throw(1);
}

int main(int argc, char* argv[])
{
    std::thread t(f1);
    t.join(); // wait for the thread to terminate
}

This call terminate() on Coliru (gcc).

Unfortunately Visual Studio 2013 will call directly abort() instead of terminate() (in my tests at least) when encountering this so even adding a handler (using std::set_handler() ) will apparently not work. I reported this to the VS team.

Still, this code will trigger an error, while your initial code is not garanteed to.

like image 75
Klaim Avatar answered Sep 30 '22 18:09

Klaim