Why does this code catch block not execute? Why does this code catch block not execute? multithreading multithreading

Why does this code catch block not execute?


You forgot to join the thread :

try {  thread t(do_work);  t.join();                                    // <<< add this  std::cerr << "THROWING" << std::endl;  throw logic_error("something went wrong");} catch (logic_error e) {  std::cerr << "GOTCHA" << std::endl;}

A joinable thread that goes out of scope, causes terminate to be called. So, you need to call either join or detach before it goes out of scope.


In C++11, 30.3.1.3, thread destructor the standard says

If joinable() then terminate(), otherwise no effects. [Note: Either implicitly detaching or joining a joinable() thread in its destructor could result in difficult to debug correctness (for detach) or performance (for join) bugs encountered only when an exception is raised. Thus the programmer must ensure that the destructor is never executed while the thread is still joinable. —end note]

Thus your program terminates once the thread destructor is called because the scope ends and the catch logic is never executed.

If you want your program to catch the exception out of the thread's scope but throw while the thread is still joinable, you'll need to catch it in the scope of the thread itself, join or detach the thread and rethrow whatever has been catched.

try {  std::thread t(foo);  try  {    std::cerr << "THROWING" << std::endl;    throw std::logic_error("something went wrong");  }  catch (...) // catch everything  {    t.join(); // join thread    throw; // rethrow  }  t.join();}catch (std::logic_error & e) {  std::cerr << "GOTCHA: " << e.what() << std::endl;}