Namespaces
Variants

std:: set_terminate

From cppreference.net
定义于头文件 <exception>
(C++11 前)
(C++11 起)

使 f 成为新的全局终止处理函数,并返回先前安装的 std::terminate_handler f 必须在不返回调用者的情况下终止程序执行,否则行为未定义。

此函数是线程安全的。每次对 std::set_terminate 的调用都会与后续对 std::set_terminate std::get_terminate 的调用形成 同步关系 (参见 std::memory_order )。

(since C++11)

目录

参数

f - 指向类型为 std::terminate_handler 的函数的指针,或空指针

返回值

先前安装的终止处理程序,若未安装任何处理程序则为空指针值。

示例

#include <cstdlib>
#include <exception>
#include <iostream>
int main()
{
    std::set_terminate([]()
    {
        std::cout << "Unhandled exception\n" << std::flush;
        std::abort();
    });
    throw 1;
}

可能的输出:

Unhandled exception
bash: line 7:  7743 Aborted                 (core dumped) ./a.out

终止处理程序同样适用于已启动的线程,因此可作为使用 try / catch 块包装线程函数的替代方案。在以下示例中,由于异常未被处理,将调用 std::terminate

#include <iostream>
#include <thread>
void run()
{
    throw std::runtime_error("Thread failure");
}
int main()
{
    try
    {
        std::thread t{run};
        t.join();
        return EXIT_SUCCESS;
    }
    catch (const std::exception& ex)
    {
        std::cerr << "Exception: " << ex.what() << '\n';
    }
    catch (...)
    {
        std::cerr << "Unknown exception caught\n";
    }
    return EXIT_FAILURE;
}

可能的输出:

terminate called after throwing an instance of 'std::runtime_error'
  what():  Thread failure
Aborted (core dumped)

随着终止处理程序的引入,可以从非主线程抛出的异常进行分析,并优雅地执行退出操作。

#include <iostream>
#include <thread>
class foo
{
public:
    foo() { std::cerr << "foo::foo()\n"; }
    ~foo() { std::cerr << "foo::~foo()\n"; }
};
// 静态对象,预期在退出时调用析构函数
foo f;
void run()
{
    throw std::runtime_error("Thread failure");
}
int main()
{
    std::set_terminate([]()
    {
        try
        {
            std::exception_ptr eptr{std::current_exception()};
            if (eptr)
            {
                std::rethrow_exception(eptr);
            }
            else
            {
                std::cerr << "Exiting without exception\n";
            }
        }
        catch (const std::exception& ex)
        {
            std::cerr << "Exception: " << ex.what() << '\n';
        }
        catch (...)
        {
            std::cerr << "Unknown exception caught\n";
        }
        std::exit(EXIT_FAILURE);
    });
    std::thread t{run};
    t.join();
}

输出:

foo::foo()
Exception: Thread failure
foo::~foo()

参阅

异常处理失败时调用的函数
(函数)
获取当前的 terminate_handler
(函数)
std::terminate 调用的函数类型
(类型定义)