The catch handler is not run. But why?
If the thread t
is started before the try
block, the catch handler runs.
If the catch block's type does not match the type thrown, the program exits explaining that the thread terminated with an uncaught exception, suggesting that the exception is handled, yet the catch block isn't run.
#include <iostream>
#include <thread>
using namespace std;
void do_work() {}
int main() {
std::cerr << "RUNNING" << std::endl;
try {
thread t(do_work);
std::cerr << "THROWING" << std::endl;
throw logic_error("something went wrong");
} catch (logic_error e) {
std::cerr << "GOTCHA" << std::endl;
}
return 0;
}
Compile command:
c++ -std=c++14 -pthread -pedantic -Wall -Wextra -O0 scratch.cpp -o scratch
You forgot to join the thread :
A joinable thread that goes out of scope, causes
terminate
to be called. So, you need to call eitherjoin
ordetach
before it goes out of scope.