brettwhiteman
brettwhiteman

Reputation: 4452

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)

Upvotes: 6

Views: 1077

Answers (1)

Klaim
Klaim

Reputation: 69682

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.

Upvotes: 3

Related Questions