首页 > 解决方案 > VC++ std::current_exception 在未捕获的异常中返回 null

问题描述

似乎 Windows 中的默认终止处理程序不会打印导致它的异常的 ex.what()。

作为一种解决方法,我想实现一个自定义终止处理程序来打印异常:

#include <iostream>

void term_func()
{
    std::cout << "term_func was called by terminate.(1)" << std::endl;
    std::exception_ptr eptr = std::current_exception();

    try
    {
        if(eptr)
        {
            std::rethrow_exception(eptr);
        }
    }
    catch(const std::exception& e)
    {
        std::cout << "Caught exception \"" << e.what() << "\"\n";
    }

    std::cout << "term_func was called by terminate.(2)" << std::endl;
    exit(-1);
}

int main(int argc, char **argv)
{
    std::set_terminate(term_func);
    throw std::runtime_error("is windows broken?");
}

这在 GCC 和 Clang++ 中运行良好(也打印异常的内容),但是在 VC++ 中它只打印:

term_func was called by terminate.(1)
term_func was called by terminate.(2)

现在,有什么解决方法吗?还是最初的问题?

标签: c++windowsexception

解决方案


推荐阅读