std::set_terminate
来自 cppreference.cn
定义于头文件 <exception> |
||
std::terminate_handler set_terminate( std::terminate_handler f ) throw(); |
(until C++11) | |
std::terminate_handler set_terminate( std::terminate_handler f ) noexcept; |
(since C++11) | |
使 f 成为新的全局 terminate 处理函数,并返回先前安装的 std::terminate_handler。f 应该终止程序的执行,且不返回其调用者,否则行为是未定义的。
此函数是线程安全的。每次调用 |
(since 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
terminate 处理函数也适用于启动的线程,因此它可以作为使用 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)
随着 terminate 处理函数的引入,可以分析从非主线程抛出的异常,并且可以优雅地执行退出。
运行此代码
#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()
[编辑] 参见
异常处理失败时调用的函数 (function) | |
(C++11) |
获取当前的 terminate_handler (function) |
由 std::terminate 调用的函数的类型 (typedef) |