sam*_*sam 7 c++ error-handling multithreading try-catch
catch处理程序未运行.但为什么?
如果在块thread t之前启动try,则捕获处理程序将运行.
如果catch块的类型与抛出的类型不匹配,程序将退出,说明线程以未捕获的异常终止,表明异常已处理,但catch块未运行.
#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;
}
Run Code Online (Sandbox Code Playgroud)
编译命令:
c++ -std=c++14 -pthread -pedantic -Wall -Wextra -O0 scratch.cpp -o scratch
Run Code Online (Sandbox Code Playgroud)
你忘了加入主题:
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;
}
Run Code Online (Sandbox Code Playgroud)
一个是超出范围可连接线,使terminate被调用.因此,您需要在其超出范围之前join或detach之前调用.