5

我希望下面的代码调用我的意外处理程序,但我的终止处理程序被调用:

#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;
}

C++ Builder 6 开发人员指南明确鼓励通过set_unexpected(). 我在做什么错,或者这只是 C++-Builder 6 中的一个错误?

4

2 回答 2

12

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

举例来说;

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;
}

输出是

我意想不到的处理程序

设置的处理程序std::set_terminate被调用std::terminate(出于参考中列出的多种原因)。这里有趣的是,当异常被抛出但未被捕获时的默认行为是调用std::terminate.

于 2014-08-20T11:35:18.113 回答
3

当发生未捕获的异常时,terminate调用。

int main()
{
    throw 1; // terminate
}

当发生意外异常时,unexpected调用。

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
}

终止的实时示例,意外

于 2014-08-20T11:44:17.457 回答