【问题标题】:Why is my terminate handler never invoked?为什么我的终止处理程序从未被调用?
【发布时间】:2015-05-12 07:07:36
【问题描述】:

我读到可以调用std::set_terminate() 来使用自己的函数作为全局异常处理程序,它会捕获所有未处理的异常。

我的程序的简化代码:

#include <exception>
#include <stdexcept>
#include <iostream>

void my_terminate_handler()
{
    std::cerr << "Terminate handler" << std::endl;

    std::cin.get();

    std::abort();
}

int main()
{
    std::set_terminate(my_terminate_handler);

    int i = 1;
    i--;

    std::cout << 1/i << std::endl;

    return 0;
}

为什么从未调用过my_terminate_handler()?在 VC++ 2013、2015 RC 和 gcc++-4.8 中。

【问题讨论】:

    标签: c++ c++11 exception-handling


    【解决方案1】:

    如果程序调用terminate,将调用终止处理程序。这可能由于各种原因而发生 - 包括未捕获的异常 - 但除以零不是这些原因之一。这给出了未定义的行为;通常,它会引发一个信号(不是 C++ 异常),您需要安装一个信号处理程序,而不是终止处理程序来捕获它。

    【讨论】:

    • 我可以在全球范围内捕获所有这些信号吗?
    • @vladon:Yes。虽然不能保证除以零会发出信号:正如我所说,它会给出未定义的行为。
    【解决方案2】:

    因为您的代码中没有未捕获的异常。加一和it gets executed

    #include <exception>
    #include <stdexcept>
    #include <iostream>
    
    void my_terminate_handler()
    {
        std::cerr << "Terminate handler" << std::endl;
    }
    
    int main()
    {
        std::set_terminate(my_terminate_handler);
    
        throw "cake";
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-22
      • 2020-10-29
      • 1970-01-01
      • 1970-01-01
      • 2015-06-03
      • 2019-09-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多