C++ 为什么不调用意外函数?

C++ 为什么不调用意外函数?,c++,exception,terminate,c++builder-6,C++,Exception,Terminate,C++builder 6,我希望以下代码调用我的意外处理程序,但调用了我的terminate处理程序: #include <except> #include <iostream> void my_terminate() { std::cerr << "my terminate handler"; std::exit(0); } void my_unexpected() { std::cerr << "my unexpected handler";

我希望以下代码调用我的意外处理程序,但调用了我的terminate处理程序:

#include <except>
#include <iostream>

void my_terminate() {
    std::cerr << "my terminate handler";
    std::exit(0);
}

void my_unexpected() {
    std::cerr << "my unexpected handler";
    std::exit(EXIT_FAILURE);
}

#pragma argsused
int main(int argc, char* argv[])
{
    std::set_terminate(my_terminate);
    std::set_unexpected(my_unexpected);
    try {
        throw std::exception();
    } catch (const std::logic_error&) {
    }
    return 0;
}
#包括
#包括
作废我的_终止(){

std::cerr当引发意外异常时,将调用调用调用std::set_unexpected
(for)设置的处理程序;而不是在未处理异常时调用。当违反动态异常规范时,将调用意外处理程序

以身作则,

void my_terminate() {
    std::cerr << "my terminate handler";
    std::exit(0);
}

void my_unexpected() {
    std::cerr << "my unexpected handler";
    std::exit(EXIT_FAILURE);
}

void function() throw() // no exception in this example, but it could be another spec
{
    throw std::exception();
}

int main(int argc, char* argv[])
{
    std::set_terminate(my_terminate);
    std::set_unexpected(my_unexpected);
    try {
        function();
    } catch (const std::logic_error&) {
    }
    return 0;
}
void my_terminate(){

std::cerr当发生未捕获异常时,调用
终止

int main()
{
    throw 1; // terminate
}
void foo() throw(int)
{
    throw "unexpected will be called.";
}

int main()
{
    foo();
}
发生意外异常时,将调用意外的

int main()
{
    throw 1; // terminate
}
void foo() throw(int)
{
    throw "unexpected will be called.";
}

int main()
{
    foo();
}
我将向您展示发生终止/意外的示例程序:

#include <cstdlib>
#include <iostream>
#include <exception>

#define TEST_TERMINATE

void my_terminate()
{
    std::cout << "terminate!" << std::endl;
    std::abort();
}
void my_unexpected()
{
    std::cout << "unexpected!" << std::endl;
    std::abort();
}

void foo() throw(int)
{
    throw "unexpected will be called.";
}

int main()
{
    std::set_terminate(my_terminate);
    std::set_unexpected(my_unexpected);

#ifdef TEST_TERMINATE
    throw 1;
#else
    foo();
#endif
}
#包括
#包括
#包括
#定义测试\u终止
作废我的_终止()
{

std::cout如果删除
catch(const std::logic_error&)
,会发生什么?@stijn您是指整个try-catch事件吗?相同。这是否意味着意外事件只处理异常规范?@Wolf,我相信是的。当违反动态异常规范时会调用它。请参阅@Wolf:yes。“预期”异常是与它离开的函数的异常规范相匹配的异常。“意外”异常是不匹配的异常。在您的示例中,异常未处理但不是意外的。是否有特定的方法来检测未捕获的异常或是
terminate()
仅在致命情况下调用?@Wolf,我认为
terminate
很不错。如果未捕获异常,则调用它。我不确定情况,但
catch(…)
捕获所有异常…?+1这也回答了我的下一个问题,我将其作为注释添加到…,但调用
终止
是否仅出于此原因?@Wolf根据
http://en.cppreference.com/w/cpp/error/terminate
,有10个案例需要调用
终止