skip to content

What happens when an exception escapes main in a C++ program, and how can a std::set_terminate handler report it before the program aborts?

level: seniorimportance: should knowfreq 45%

answer

  1. no handler anywhere
  2. unwinding is implementation-defined
  3. the handler must not return
  4. current_exception still works there

basics

~20 s

No handler matches, so std::terminate is called; whether the stack is unwound first is implementation-defined, and the default handler calls abort. A handler installed with std::set_terminate can rethrow std::current_exception() to log what() and then must end the program, for example with std::abort.

solid answer

~40 s

An exception with no matching handler, including one that escapes `main` or a thread's initial function, calls `std::terminate`. Whether destructors run first is implementation-defined; in a run with libc++ the local log object's destructor did not run. `std::terminate` calls the current `terminate_handler`: the default calls `abort()`, after libc++abi prints `terminating due to uncaught exception of type std::runtime_error: ...` and libstdc++'s verbose handler prints a similar line with `what()`. Your own handler, set with `std::set_terminate`, can call `std::current_exception()`, which still refers to the exception because terminate counts as an active implicit handler, rethrow it in a local `try`, log the message, and then end the process: a terminate handler must not return. For a CLI tool, catching in `main` and returning `EXIT_FAILURE` is still better, since it runs every destructor.

code

cpp · 24 lines
cpp
#include <cstdio>
#include <cstdlib>
#include <exception>
#include <iostream>
#include <stdexcept>

struct LogFile {
    ~LogFile() { std::cerr << "log flushed\n"; }   // runs only if the stack unwinds
};

[[noreturn]] void on_terminate() {
    if (auto p = std::current_exception()) {
        try { std::rethrow_exception(p); }
        catch (const std::exception& e) { std::cerr << "fatal: " << e.what() << '\n'; }
        catch (...) { std::cerr << "fatal: unknown exception\n"; }
    }
    std::abort();                                   // a terminate handler must not return
}

int main() {
    std::set_terminate(on_terminate);
    LogFile log;
    throw std::runtime_error("config file missing");
}

go deeper

for a junior

Know that an exception nobody catches ends the program through std::terminate, and that catching in main is how a tool fails cleanly.

for a middle

Explain that unwinding is implementation-defined when no handler matches and that the default terminate handler calls abort.

for a senior

Install a terminate handler that rethrows std::current_exception to log the message, never returns, and keeps its work minimal.

for a principal

Make top-level catch blocks and a logging terminate handler mandatory for every binary and thread entry point, so crashes always leave a reason.

## The sequence when nothing catches When a thrown exception finds no matching handler in any enclosing `try` block of its thread, the C++ standard calls **`std::terminate`**. For this situation the standard adds that it is **implementation-defined whether the stack is unwound** before the call. So destructors of local objects between the `throw` and the top of the stack may or may not run. In a run with Apple clang and libc++, a `LogFile` local to `main` whose destructor printed "log flushed" printed nothing, and the process exited with status 134, the usual shell status for `SIGABRT`. `std::terminate` then calls the current **`terminate_handler`**. The standard requires every handler to terminate the program without returning, and says the implementation's default handler calls `abort()`. ## What the default handlers print The standard does not require a message, but both mainstream libraries print one: - libc++abi, in the run here: `libc++abi: terminating due to uncaught exception of type std::runtime_error: config file missing`. - libstdc++'s default is its verbose terminate handler; its manual says it obtains the name of the current exception, demangles it and prints it to `stderr`, including `what()` for types derived from `std::exception`, with output beginning `terminate called after throwing an instance of`. ## Writing your own terminate handler `std::set_terminate(f)` installs `f` and returns the previous handler; `std::get_terminate()` reads the current one. A useful handler for a daemon: 1. Calls `std::current_exception()`. When terminate is entered because of a throw, the standard treats an **implicit handler as active**, so the uncaught exception is the currently handled exception and the pointer is non-null. When terminate was called for another reason, it can be null. 2. If non-null, rethrows it inside a local `try` with `std::rethrow_exception` and catches `const std::exception&` to log `what()`, plus `catch (...)` for anything else. 3. Calls `std::abort()` (or `std::_Exit` with a chosen status). Returning is not allowed. Keep the handler minimal: it runs in a broken state, possibly during unwinding, and must not allocate heavily or take locks that the failing code might hold. ## Better: catch at the top A terminate handler is a last report, not error handling. For the command-line build tool that CI runs, the better structure is: ```cpp int main(int argc, char** argv) { try { return run(argc, argv); } catch (const std::exception& e) { std::cerr << "fatal: " << e.what() << ' '; return EXIT_FAILURE; } catch (...) { std::cerr << "fatal: unknown exception "; return EXIT_FAILURE; } } ``` Now the stack is unwound to `main`'s handler, every destructor runs, the status is `EXIT_FAILURE` instead of an abort, and CI shows a clean failure with a message. A run of the same `LogFile` program restructured this way printed "log flushed", then the fatal line, and exited with status 1. ## Terminate in a multithreaded process `std::terminate` ends the whole process, not one thread. When a worker thread's exception escapes: - the terminate handler runs on that worker thread; - when the handler ends with `std::abort`, as the default does, the other threads are stopped wherever they are, with no destructors and no `atexit` handlers; - a log line still in some other thread's buffer is lost unless the handler flushes it. That is why the handler should be installed in `main` before any thread starts, should write with as little machinery as possible, and should not wait on locks that another thread might hold. Catching at the top of every thread function and handing the exception to the joining thread keeps most failures out of this path. ## Other ways to reach `std::terminate` The same function is called, by the standard's own list, when an exception escapes a thread's initial function, a `noexcept` function or a destructor during unwinding; when a static object's constructor or destructor exits via an exception; when an `atexit` or `at_quick_exit` handler exits via one; when `throw;` runs with no exception being handled; and when a joinable `std::thread` is destroyed. A terminate handler that logs `std::current_exception()` covers the exception cases; for the others the pointer may be null, so the handler should log that too. ## Checklist - Catch `std::exception` and `...` at the top of `main` and of each thread function. - Install a terminate handler early that logs and aborts. - Do not rely on destructors running when nothing catches.

  • Why can a terminate handler call std::current_exception for an uncaught exception?
    The standard says an implicit handler is considered active when `std::terminate` is entered due to a throw, and the currently handled exception is the one with the most recently activated, still active handler. So inside the terminate handler the uncaught exception counts as handled and `std::current_exception()` returns it. If terminate was called for another reason, such as a joinable `std::thread` being destroyed, it may return a null pointer.
  • Do destructors run when an exception escapes main?
    The standard leaves it implementation-defined whether the stack is unwound when no matching handler is found. On the libc++ run here they did not. Portable code therefore assumes they might not and catches at the top of `main`, which guarantees unwinding to that handler and a normal return.

  • An uncaught exception always unwinds the stack and runs destructors.
  • A terminate handler can log the error and return to continue.
  • std::current_exception is always null inside a terminate handler.
  • An uncaught exception makes main return EXIT_FAILURE.