命名空间
变体
操作

std::set_terminate

来自 cppreference.cn
< cpp‎ | 错误
定义于头文件 <exception>
(C++11 前)
std::terminate_handler set_terminate( std::terminate_handler f ) noexcept;
(C++11 起)

f 设置为新的全局 terminate 处理函数,并返回先前安装的 std::terminate_handlerf 必须终止程序执行而不能返回其调用者,否则行为未定义。

此函数是线程安全的。每次调用 std::set_terminate 都与(参见 std::memory_order)后续调用 std::set_terminatestd::get_terminate 进行同步。

(C++11 起)

目录

[编辑] 参数

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

[编辑] 返回值

先前安装的 terminate 处理函数,如果未安装则为空指针值。

[编辑] 示例

#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"; }
};
 
// Static object, expecting destructor on exit
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 调用的函数类型
(类型定义) [编辑]