From cppreference.com
Defined in header
std::terminate_handlerset_terminate(std::terminate_handlerf)throw();(until C++11)std::terminate_handlerset_terminate(std::terminate_handlerf)noexcept;(since C++11)Makes f the new global terminate handler function and returns the previously installed
. f shall terminate execution of the program without returning to its caller, otherwise the behavior is undefined.
This function is thread-safe. Every call to std::set_terminatesynchronizes-with (see
) subsequent calls to std::set_terminate and
.
(since C++11)Parameters
Return value
The previously-installed terminate handler, or a null pointer value if none was installed.
Example
Run this code
#include<cstdlib>#include<exception>#include<iostream>intmain(){std::set_terminate([](){std::cout<<"Unhandled exception\n"<<std::flush;std::abort();});throw1;}Possible output:
Unhandled exception bash: line 7: 7743 Aborted (core dumped) ./a.out The terminate handler will also work for launched threads, so it can be used as an alternative to wrapping the thread function with a try/catch block. In the following example, since the exception is unhandled,
will be called.
Run this code
#include<iostream>#include<thread>voidrun(){throwstd::runtime_error("Thread failure");}intmain(){try{std::threadt{run};t.join();returnEXIT_SUCCESS;}catch(conststd::exception&ex){std::cerr<<"Exception: "<<ex.what()<<'\n';}catch(...){std::cerr<<"Unknown exception caught\n";}returnEXIT_FAILURE;}Possible output:
terminate called after throwing an instance of 'std::runtime_error' what(): Thread failure Aborted (core dumped) With the introduction of the terminate handler, the exception thrown from the non-main thread can be analyzed, and exit can be gracefully performed.
Run this code
#include<iostream>#include<thread>classfoo{public:foo(){std::cerr<<"foo::foo()\n";}~foo(){std::cerr<<"foo::~foo()\n";}};// Static object, expecting destructor on exitfoof;voidrun(){throwstd::runtime_error("Thread failure");}intmain(){std::set_terminate([](){try{std::exception_ptreptr{std::current_exception()};if(eptr){std::rethrow_exception(eptr);}else{std::cerr<<"Exiting without exception\n";}}catch(conststd::exception&ex){std::cerr<<"Exception: "<<ex.what()<<'\n';}catch(...){std::cerr<<"Unknown exception caught\n";}std::exit(EXIT_FAILURE);});std::threadt{run};t.join();}Output:
foo::foo() Exception: Thread failure foo::~foo() See also