std::set_terminate
From cppreference.com
| ヘッダー <exception> で定義 |
||
std::terminate_handler set_terminate( std::terminate_handler f ) throw(); |
(C++11まで) | |
| std::terminate_handler set_terminate( std::terminate_handler f ) noexcept; |
(C++11以降) | |
f を新しいグローバルなterminateハンドラ関数に設定し、以前にインストールされていた std::terminate_handler を返します。f は、呼び出し元に戻ることなくプログラムの実行を終了する必要があります。それ以外の場合、動作は未定義となります。
|
この関数はスレッドセーフです。 |
(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()
[編集] 関連項目
| 例外処理が失敗した際に呼び出される関数 (関数) | |
| (C++11) |
現在の terminate_handler を取得する (関数) |
| std::terminate によって呼び出される関数の型 (typedef) |