工作线程中的C ++未捕获异常

时间:2018-01-31 05:33:04

标签: c++ multithreading uncaught-exception stack-unwinding

未捕获的异常对主线程和另一个std :: thread表现不同。

这是测试程序

#include <thread>

class XXX{
public:
  XXX(){std::fprintf(stderr, "XXX ctor\n");}
  ~XXX(){std::fprintf(stderr, "XXX dtor\n");}
};

void mytest(int i)
{
    XXX xtemp;
    throw std::runtime_error("Hello, world!");
}
int main(int argc, char *argv[])
{
    if(argc == 1) {
        mytest(0);
    }else{
        std::thread th([&]{mytest(0);});
        th.join();
    }
}

上面的代码(C ++ 11),由GCC 5.4编译 没有args运行

XXX ctor
terminate called after throwing an instance of 'std::runtime_error'
   what():  Hello, world!
Aborted (core dumped)

运行1 arg:

XXX ctor
XXX dtor
terminate called after throwing an instance of 'std::runtime_error'
  what():  Hello, world!
Aborted (core dumped)

所以堆栈展开是在工作线程中执行的,而不是在主线程中执行,为什么?

我问,因为我喜欢核心转储,以便在两种情况下提供有用的堆栈回溯信息(对于未捕获的异常)。

提前致谢!!!

进一步的试验表明,将 noexcept 关键字添加到线程函数体mytest()可以部分解决我的问题,因为展开会失败,但它不是一个好的解决方案,因为如果mytest(),unwind仍会部分发生正在调用另一个没有noexcept保证的函数,实际上抛出了未捕获的异常。

更新:感谢所有评论提供者,现在我理解C ++异常不是回溯友好的,GCC作为C ++实现,可以自由选择在主线程抛出未捕获异常时不放松,并从工人线程。

更新:特别感谢Sid S&amp; Jive Dadson,我必须混淆一些概念:1)异常/错误处理; 2)运行时断言3)段故障,2&amp; 3类似,它们是UN可恢复的错误,立即中止是唯一的选择,它们在调试器中也是回溯友好的,因为不涉及堆栈展开。它们不应该使用异常概念来实现。异常应该始终被捕获,让未被捕获的异常离开main()不是推荐用法。

2 个答案:

答案 0 :(得分:2)

您应该在发生它的线程中捕获异常。默认处理程序将调用terminate(),无论它在何处,展开或不取决于实现。

答案 1 :(得分:2)

为什么呢?这就是它的方式。从c ++ 11开始,对于处理除main之外的线程中抛出的异常有一些支持,但是你需要检测线程以捕获异常并重新抛出异常。这是怎么回事。

#include <thread>
#include <iostream>

class XXX {
public:
    XXX() { std::fprintf(stderr, "XXX ctor\n"); }
    ~XXX() { std::fprintf(stderr, "XXX dtor\n"); }
};

void mytest(int i)
{
    XXX xtemp;
    throw std::runtime_error("Hello, world!");
}

int main(int argc, char *argv[])
{
    std::exception_ptr exception_ptr = nullptr;
    if (argc == 1) {
        mytest(0);
    }
    else {
        std::thread th([&exception_ptr]() {
            try {
                mytest(0);
            }
            catch (...) {
                exception_ptr = std::current_exception();
            }
        });
        th.join();
        if (exception_ptr) {
            try {
                std::rethrow_exception(exception_ptr);
            }
            catch (const std::exception &ex)
            {
                std::cerr << "Thread exited with exception: " << ex.what() << "\n";
            }
        }
    }
}