using std::terminate or “how to call that last function before the end of everything”


std::terminate is called when exception handling fails, if:

  • an exception was thrown and not handled
  • the constructor or the destructor of a static or thread-local object throws an exception
  • a noexcept specification is violated (exception is thrown in a function declared noexcept)
  • …and many others – But these are the top reasons.


The goal of std::terminate is to call the terminate handler function which can be registered via std::set_terminate. By default, terminate is simply calling std::abort, which is throwing SIGABRT signal to the OS.

Functions we will discuss about

std::terminate can be called even before globals or thread_locals or class statics have been initialized (due to throws in the global initialization for example), so we cannot rely on any of that. The only thing we can rely on are the STD globals: cin, cout, cerr, clog, win, wout, werr, wlog – which are guaranteed to be valid at that point.

What you can do in the terminate handler, for example, would be to pause the thread of execution for some time, in order for other threads to finish their tasks before the application is closed.
Other than that, we can rely on functions such as std::current_exception to get the current exception and log it, for example.

We can use the following code to make sure that the terminate handler function is set before main.

You may also like...

Leave a Reply