为什么我的终止处理程序从未被调用?

Why is my terminate handler never invoked?

我读到可以调用 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.

如果程序调用 terminate,将调用终止处理程序。发生这种情况的原因有很多——包括未捕获的异常——但被零除不是其中一个原因。这给出了未定义的行为;通常,它会引发一个信号(不是 C++ 异常),您需要安装一个信号处理程序,而不是终止处理程序来捕获它。

因为你的代码中没有未捕获的异常。加一 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";
}