§The Annotated C++ StandardC++ 标准注疏 中文

How C++ exceptions are implemented

The table-driven exception handling of the Itanium ABI that GCC and Clang use on non-Windows platforms: which runtime functions a throw calls, how two-phase unwinding finds a handler, how landing pads destroy objects and enter catch clauses, how noexcept and -fno-exceptions affect code generation, and what zero-cost really costs.

exceptionsABIItaniumcode generationtoolchain

Key points

  • throw compiles to two runtime calls: __cxa_allocate_exception allocates the exception object (not through operator new), and __cxa_throw starts unwinding. The non-throwing path has no extra instructions at all.
  • Unwinding takes two passes: the first looks for a handler frame by frame, read-only; only once one is found does the second pass run destructors and enter the handler. If no handler is found, std::terminate is called directly, with the stack not unwound at all.
  • Each function's LSDA table records which call site maps to which landing pad and which types it can catch; the CFI in .eh_frame records how to get from a frame to its caller.
  • Clang implements noexcept as a catch (...) wrapping the whole function body plus std::terminate, so unwinding stops at that function, and its own local objects aren't destroyed.
  • Zero-cost means no extra instructions on the normal path. A throw takes several microseconds, the exception tables take space, and calls that may throw also constrain optimization.

The freedom the standard leaves#

Chapter 14 of the standard ([except]) specifies only the semantics of exception handling and leaves the implementation to implementations:

  • the memory for the exception object is allocated in an unspecified way ([except.throw]/4);
  • when no matching handler is found, it is implementation-defined whether the stack is unwound before std::terminate is called ([except.handle]/8);
  • when an exception leaves a noexcept function, the stack may be unwound fully, partially or not at all ([except.terminate]/2).

GCC and Clang on Linux, macOS and similar platforms use the exception handling scheme of the Itanium C++ ABI. Despite the Itanium in its name, it is in practice the C++ ABI of nearly every non-Windows platform today. Below we use assembly generated by Homebrew Clang 23 to see how these freedoms are used.

Test setup

x86-64 Linux assembly is generated with clang++ -std=c++2c -O1 -S --target=x86_64-linux-gnu, compiling only without linking; run times and sizes are measured on macOS arm64 on our test machine.

Two layers of runtime#

The Itanium scheme divides the work between two libraries:

Layer Components Responsibilities
Language-independent unwind library _Unwind_RaiseException, _Unwind_Resume and so on (libgcc_s, LLVM libunwind, macOS's system libunwind) Restores registers frame by frame from the frame descriptions in .eh_frame; calls each frame's personality routine
C++ runtime The __cxa_* functions and __gxx_personality_v0 (libsupc++ or libc++abi) Allocates exception objects, implements C++ type matching, parses LSDAs, tracks the currently handled exception

The unwind library knows nothing about C++. It only knows that the call stack consists of frames, each of which has a personality routine (a language-specific callback) it can ask. That is how frames from C, C++ and other languages can be mixed in one call stack and unwound together.

Throwing#

C++eh.cpp
struct Guard { ~Guard(); };
struct Err { int code; };
void may_throw(int);

void thrower(int x) {
    if (x < 0) throw Err{x};
}

int catcher(int x) {
    Guard g;
    try {
        may_throw(x);
    } catch (const Err& e) {
        return e.code;
    }
    return 0;
}

The assembly for thrower, with some directives removed:

_Z7throweri:
        testl   %edi, %edi
        js      .LBB0_2
        retq                            # normal path: one test, one return
.LBB0_2:
        pushq   %rbx
        movl    %edi, %ebx
        movl    $4, %edi                # sizeof(Err)
        callq   __cxa_allocate_exception@PLT
        movl    %ebx, (%rax)            # construct the exception object in the returned memory
        leaq    _ZTI3Err(%rip), %rsi    # second argument: typeid(Err)
        movq    %rax, %rdi              # first argument: the exception object
        xorl    %edx, %edx              # third argument: destructor pointer, null since Err is trivially destructible
        callq   __cxa_throw@PLT         # doesn't return

The normal path (x >= 0) has no exception-related instructions at all. The throwing path does three things.

__cxa_allocate_exception(size) allocates storage for the exception object. In front of the user-visible object it allocates an extra runtime header, __cxa_exception, holding the type information, the destructor pointer, a reference count, a handler count, and the _Unwind_Exception the unwind library needs. Implementations usually use malloc, falling back to a preallocated emergency buffer on failure. The standard makes the storage unspecified and says the global operator new is not called here ([basic.stc.dynamic.allocation]/5) precisely to allow this.

Next the exception object is constructed in place in that memory ([except.throw]/3). Err is an aggregate, so it is just one movl; for class types a constructor is called here. If the constructor throws, compiler-generated cleanup code calls __cxa_free_exception to release the memory, and what propagates outward is the exception the constructor threw. This is consistent with [except.throw]/6, which says an exception is considered uncaught only after initialization of the exception object completes.

Finally __cxa_throw(obj, type_info*, destructor) records the type and destructor, increments the uncaught exception count (which is what std::uncaught_exceptions() reads), and calls _Unwind_RaiseException. That only returns if no handler is found, in which case __cxa_throw calls std::terminate.

Two-phase unwinding#

_Unwind_RaiseException walks the call stack twice.

  1. Search phase: starting at the throw point and moving outward frame by frame, it calls each frame's personality routine to ask whether that frame has a handler that can catch this exception. This pass is read-only: it runs no destructors and modifies no frames.
  2. Cleanup phase: once a handler is found, it starts again at the throw point and moves outward. In this pass the personality routine transfers control into each frame's landing pad, running destructors and other cleanup, until it reaches the frame with the handler and enters the handler itself.

If the search phase reaches the bottom of the stack without a handler, _Unwind_RaiseException returns an error, __cxa_throw calls std::terminate, and the stack hasn't been unwound at all. This is the choice mainstream implementations make under [except.handle]/8. The benefit is that a core dump produced by an uncaught exception still contains the full call stack of the throw point.

The cost of two passes is that every throw walks the stack twice, parsing frame descriptions and LSDAs both times. This is one of the main reasons throwing is expensive.

Frame descriptions: .eh_frame and CFI#

To get from a frame to its caller, the unwind library must know, at the current instruction, where the return address is stored, how far the stack pointer has moved, and where on the stack the registers that need restoring were saved. The compiler writes this information into the .eh_frame section as DWARF Call Frame Information (CFI). In assembly these are the .cfi_* directives:

_Z7catcheri:
        .cfi_startproc
        .cfi_personality 155, DW.ref.__gxx_personality_v0   # this function's personality routine
        .cfi_lsda 27, .Lexception0                          # where this function's LSDA is
        pushq   %rbx
        .cfi_def_cfa_offset 16
        subq    $16, %rsp
        .cfi_def_cfa_offset 32
        .cfi_offset %rbx, -16

llvm-dwarfdump --eh-frame decodes them into a table. The entry for thrower is:

  0x0: CFA=RSP+8: RIP=[CFA-8]
  0x6: CFA=RSP+16: RBX=[CFA-16], RIP=[CFA-8]

This means that after offset 6, the canonical frame address (CFA) is RSP+16, RBX is saved at CFA-16, and the return address is at CFA-8. The unwind library interprets tables like this to walk outward one frame at a time.

In .eh_frame each function has an FDE (Frame Description Entry), and several functions share a CIE (Common Information Entry). For functions with a personality routine, the CIE's augmentation string contains P (personality) and L (LSDA); in the dump on our test machine it is Augmentation: "zPLR".

macOS

On Apple platforms the compiler also generates a __LD,__compact_unwind section, which the linker converts into the more compact __TEXT,__unwind_info. Frames that can be described with the compact encoding no longer need a DWARF FDE. The arm64 object files on our test machine have both a __compact_unwind and a __gcc_except_tab section. The formats differ, but the two-phase model, personality routines and LSDAs are the same.

Personality routines and the LSDA#

The unwind library calls, for each frame, the personality routine recorded in its CIE. The personality routine for C++ code is __gxx_personality_v0; GCC and Clang both use that name, and libc++abi and libsupc++ each have an implementation. It reads the function's LSDA (Language-Specific Data Area, in the .gcc_except_table section) and answers two questions:

  • Search phase: does the current call site have a handler that matches this exception type?
  • Cleanup phase: where is the current call site's landing pad, and which selector should the landing pad be given?

The LSDA for catcher, with comments generated by Clang:

GCC_except_table1:
.Lexception0:
        .byte   255                     # @LPStart Encoding = omit
        .byte   155                     # @TType Encoding = indirect pcrel sdata4
        .uleb128 .Lttbase0-.Lttbaseref0
        .byte   1                       # Call site Encoding = uleb128
        .uleb128 .Lcst_end0-.Lcst_begin0
.Lcst_begin0:
        .uleb128 .Ltmp0-.Lfunc_begin0   # >> Call Site 1 <<
        .uleb128 .Ltmp1-.Ltmp0          #   Call between .Ltmp0 and .Ltmp1
        .uleb128 .Ltmp2-.Lfunc_begin0   #     jumps to .Ltmp2
        .byte   3                       #   On action: 2
        .uleb128 .Ltmp1-.Lfunc_begin0   # >> Call Site 2 <<
        .uleb128 .Ltmp3-.Ltmp1          #   Call between .Ltmp1 and .Ltmp3
        .byte   0                       #     has no landing pad
        .byte   0                       #   On action: cleanup
        ...
.Lcst_end0:
        .byte   0                       # >> Action Record 1 <<
                                        #   Cleanup
        .byte   0                       #   No further actions
        .byte   1                       # >> Action Record 2 <<
                                        #   Catch TypeInfo 1
        .byte   125                     #   Continue to action 1
                                        # >> Catch TypeInfos <<
.Ltmp6:                                 # TypeInfo 1
        .long   .L_ZTI3Err.DW.stub-.Ltmp6

The LSDA consists of three tables.

The call-site table maps instruction ranges within the function to landing pad addresses and actions. Entry 1 says that an exception thrown between .Ltmp0 and .Ltmp1 (that is, call may_throw) jumps to .Ltmp2 and performs action 2. If a call that isn't in any range throws, the personality routine calls std::terminate. So the compiler lists every call that may throw, even if it has no landing pad.

The action table: action 2 is "if it matches entry 1 of the type table, the selector is 1, otherwise continue with action 1"; action 1 is cleanup, meaning run destructors only and then keep unwinding.

The type table: entry 1 is typeid(Err). A null pointer means catch (...).

The matching rules of [except.handle]/3 are implemented in the personality routine: it compares the exception object's type_info (the second argument to __cxa_throw) with the type_info of the handlers in the type table. Derived-to-base matching relies on the base class lists recorded in __si_class_type_info and __vmi_class_type_info, including whether a base is public and whether it is ambiguous; pointer matching relies on the cv-qualifiers and noexcept flag recorded in __pointer_type_info. The runtime has only type_info to work with, which also explains why handler matching doesn't allow arbitrary type conversions.

Landing pads: destruction and catch#

The code for catcher:

        xorl    %ebx, %ebx
.Ltmp0:
        callq   _Z9may_throwi@PLT       # call site 1
.Ltmp1:
.LBB1_3:                                # where the normal path and the post-catch path meet
        leaq    15(%rsp), %rdi
        callq   _ZN5GuardD1Ev@PLT       # ~Guard()
        movl    %ebx, %eax
        addq    $16, %rsp
        popq    %rbx
        retq
.LBB1_1:                                # landing pad .Ltmp2
.Ltmp2:
        movq    %rax, %rbx              # rax = _Unwind_Exception*
        cmpl    $1, %edx                # edx = selector; 1 means Err matched
        jne     .LBB1_5                 # not Err: cleanup only
        movq    %rbx, %rdi
        callq   __cxa_begin_catch@PLT   # returns the exception object's address; the handler becomes active
        movl    (%rax), %ebx            # e.code
.Ltmp3:
        callq   __cxa_end_catch@PLT     # the handler exits
.Ltmp4:
        jmp     .LBB1_3                 # carry on: destroy g, return
.LBB1_4:
.Ltmp5:
        movq    %rax, %rbx
.LBB1_5:                                # landing pad for cleanup
        leaq    15(%rsp), %rdi
        callq   _ZN5GuardD1Ev@PLT       # destroy g during stack unwinding
        movq    %rbx, %rdi
        callq   _Unwind_Resume@PLT      # continue unwinding outward

The normal path destroys g and returns right after call may_throw, with no checks whatsoever.

The personality routine jumps into the landing pad during the cleanup phase, with %rax holding a pointer to the exception header and %edx the selector. If the selector isn't 1, it jumps to the cleanup landing pad: destroy g ([except.ctor]/2), then _Unwind_Resume hands control back to the unwind library to continue with the outer frames.

__cxa_begin_catch marks the exception as caught (decrementing the uncaught count, [except.throw]/8), increments the handler count, pushes the exception onto the stack of caught exceptions, and returns the exception object's address. The top of that stack is what [except.handle]/10 calls the currently handled exception. When catching by reference, e binds directly to that address; when catching by value, the compiler calls the copy constructor after this.

__cxa_end_catch is called when the handler exits. It decrements the handler count, and if the count reaches zero and the exception hasn't been rethrown, it calls the recorded destructor to destroy the exception object and frees the memory. This corresponds to the first potential destruction point in [except.throw]/4. If a std::exception_ptr still refers to the object, the reference count defers destruction until the last exception_ptr is destroyed, the second potential destruction point.

__cxa_end_catch is itself in the call-site table (entry 3, landing pad .Ltmp5), because the exception object's destructor may throw, and g must still be cleaned up then.

throw; compiles to __cxa_rethrow(). It marks the currently handled exception as rethrown, counts it as uncaught again, and calls _Unwind_RaiseException once more, without creating a new exception object ([expr.throw]/3).

noexcept and code generation#

Compare two functions that differ only in noexcept:

C++nx.cpp
struct Guard { ~Guard(); };
void may_throw(int);
void f(int x) noexcept { Guard g; may_throw(x); }
void h(int x)          { Guard g; may_throw(x); }

h may throw; its landing pad destroys g and continues unwinding:

.LBB2_2:
        movq    %rax, %rbx
        leaq    15(%rsp), %rdi
        callq   _ZN5GuardD1Ev@PLT
        movq    %rbx, %rdi
        callq   _Unwind_Resume@PLT

f is noexcept; its landing pad and LSDA are:

.LBB0_2:
        movq    %rax, %rdi
        callq   __clang_call_terminate     # = __cxa_begin_catch + std::terminate
...
                                           # in the LSDA:
        .byte   1                          # >> Action Record 1 <<
                                           #   Catch TypeInfo 1
        .long   0                          # TypeInfo 1 = 0, i.e. catch (...)

Clang implements noexcept as a catch (...) wrapping the whole function body, whose handler calls std::terminate. The search phase finds this handler, so the cleanup phase unwinds only as far as f, and frames deeper than f are destroyed as usual.

f's own g isn't destroyed; the landing pad terminates directly, saving the cleanup code. This is what the partial unwinding permitted by [except.terminate]/2 is for. A run verifying this is in [except.special].

__clang_call_terminate first calls __cxa_begin_catch and then std::terminate, so the exception becomes the currently handled exception. This corresponds to [except.handle]/9: when std::terminate is entered because of a throw, an implicit handler is considered active. A terminate handler can therefore get the exception with std::current_exception().

The bigger gain is on the caller's side. When the called function is noexcept, the call site needs no landing pad in the LSDA. If none of the calls in a function can throw, it may need no LSDA or personality routine at all.

What zero-cost really costs#

Zero-cost means no extra instructions on the normal path when nothing is thrown. There are still costs elsewhere:

Cost Explanation
Throwing is slow It allocates an exception object, walks the stack twice, parses CFI and LSDAs, compares type_infos, and for dynamically loaded modules has to find their .eh_frame. On our test machine (Apple M-series, libc++abi, -O2), a throw/catch across a single function call takes about 3 µs, while an ordinary return with the same structure takes under 1 ns.
Binary size Landing pad code, LSDAs and CFI all take space. On our test machine, a small function calling vector::push_back and to_string has an 820-byte __text section at -O2, 532 bytes with -fno-exceptions, which also drops 36 bytes of __gcc_except_tab and 224 bytes of __compact_unwind.
Constrained optimization Every call that may throw is an implicit control-flow edge. The compiler can't freely move memory writes across such a call, because the exception path might observe them; landing pads extend variables' live ranges, increase register pressure and affect inlining decisions.
Cache Landing pads usually go at the end of the function or in a separate cold code region, so the impact on the instruction cache is generally small, but not zero.
Throwing from many threads On some platforms, looking up .eh_frame (for example glibc's dl_iterate_phdr) causes lock contention when many threads throw frequently; newer runtimes have optimized this. The difference varies by platform and version, so measure.

Hence the common engineering guideline: use exceptions for failures that are unlikely and need to propagate across many levels of calls, not for ordinary control flow.

-fno-exceptions#

GCC and Clang both provide -fno-exceptions, which makes the compiler accept a non-conforming dialect. Compiling eh.cpp above in this mode, Clang 23 reports:

eh.cpp:6:16: error: cannot use 'throw' with exceptions disabled
eh.cpp:11:5: error: cannot use 'try' with exceptions disabled

In this mode no landing pads or LSDAs are generated. The example measured on macOS above even lost its __compact_unwind. On Linux, whether .eh_frame is still generated depends on other options such as -fasynchronous-unwind-tables; debuggers and profilers need it too.

Where the standard library would throw, libc++ and libstdc++ usually terminate the program directly instead, for example by calling std::abort.

Take care when mixing with code compiled with exceptions. If an exception passes through a frame compiled with -fno-exceptions, that frame's local objects aren't destroyed, because there is no landing pad; whether it can pass through at all depends on whether CFI is still present. This is a class of bug that is hard to spot.

Many large codebases, such as game engines, some browsers and embedded projects, use this dialect for reasons of size, predictability or history. It isn't standard C++: [intro.compliance] requires even freestanding implementations to support exceptions.

The MSVC model#

Not verified on our test machine

There is no MSVC on our test machine. What follows comes from public documentation and is only an overview.

On x86-64 and ARM64 Windows, MSVC also uses a table-driven scheme. A function's unwind information is recorded in the .pdata and .xdata sections of the PE file. A C++ throw (_CxxThrowException) is built on Windows structured exception handling (SEH), and the __CxxFrameHandler family of functions plays a role similar to a personality routine, likewise searching first and unwinding afterwards.

The older scheme on 32-bit x86 Windows registers on the stack: every function that contains a try or needs cleanup links a record into a per-thread list on entry, and updates a state number during execution. This has a real instruction cost on the normal path, exactly what the zero-cost model avoids.

The compile option /EHsc catches only C++ exceptions and assumes extern "C" functions don't throw; /EHa lets catch (...) catch SEH exceptions too, such as access violations.

When MSVC throws, the exception object lives on the stack, and the stack frames of the throw point haven't been popped while the handler runs. This is one of the practical reasons the standard allows std::current_exception() to return a copy of the exception object ([propagation]/9).

Summary#

Step Itanium ABI implementation
Allocating the exception object __cxa_allocate_exception: malloc plus an emergency buffer, no call to operator new
Starting the throw __cxa_throw → _Unwind_RaiseException
Finding a handler Search phase: each frame's personality routine reads the LSDA's call-site, action and type tables
Moving between frames DWARF CFI in .eh_frame (mostly compact unwind on macOS)
Destroying local objects The cleanup phase jumps into landing pads, then _Unwind_Resume after destruction
Entering and leaving catch __cxa_begin_catch, __cxa_end_catch; the latter destroys the exception object when the last handler exits
No handler std::terminate, stack not unwound
noexcept A catch (...) around the function body plus std::terminate, unwinding only to this frame