编译器:g ++ 9.2.0作业系统:Windows 10g ++调用:
g++ -E main.cpp -v -o main.i
g++ -c main.cpp -v -o main.o
g++ main.o -v -o main.exe
main.exe
main.cpp:
#include <chrono>
#include <iostream>
#include <string>
#include <exception>
#include <iostream>
//#include <thread>
#include "mingw.thread.h"
struct Object{
struct Exception : public std::exception{
std::string error_;
Exception(std::string str){
this->error_ = str;
}
~Exception() {
}
std::string get(){
return error_;
}
};
void DoSomeWork() {
try {
std::thread AnotherTh(&Object::GenerateException ,this);
AnotherTh.detach ();
while(true);
}
catch (...) {
throw ;
}
}
void GenerateException(){
std::this_thread::sleep_for (std::chrono::seconds(5));
throw Object::Exception ("Some error");
}
};
int main(){
try{
Object instance;
std::thread th(&Object::DoSomeWork,std::ref(instance));
th.join ();
}
catch (Object::Exception &ex ) {
std::cout << ex.get ();
}
catch (std::exception &ex ){
std::cout << ex.what ();
}
catch (...){
}
std::cout << "never reach this";
return 0;
}
输出:
terminate called after throwing an instance of 'Object::Exception'
what(): std::exception
我正在用新线程(th)启动主线程并等待它,在th内部启动另一个线程,将引发异常。因此,当它出现时,开始展开堆栈释放(从Object :: GenerateException到Object :: DoSomeWork,因为不再有调用是Object :: GenerateException的堆栈),并且管理传递给Object :: DoSomeWork的try-catch,存在相同的问题调用链到main的try-catch作为Object :: DoSomeWork“知道”它是从main调用的。我不明白为什么它不能处理异常并将其传递给main的try-catch。
因为代码:
std::thread AnotherTh(&Object::GenerateException ,this);
AnotherTh.detach ();
while(true);
在其他线程中引发异常。