为什么我的终止处理程序永远不会被调用?

时间:2015-05-12 07:07:37

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

我已经读过,可以调用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。

2 个答案:

答案 0 :(得分:13)

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

答案 1 :(得分:4)

因为代码中没有未捕获的异常。添加一个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";
}
相关问题