Exception Handling Internals
C++ exceptions have a reputation for being expensive. The truth is messier. Modern implementations use "zero-cost" exceptions: nothing on the normal path, the bill arrives only when something actually gets thrown. This lesson digs into how that works at the binary level — DWARF unwinding tables, the .eh_frame section, and the runtime machinery wired up behind every try/catch.
How Exceptions Work: The Overview
When you throw in C++:
- The runtime allocates memory for the exception object
- It walks up the call stack hunting for a matching
catchhandler - As it crosses each frame, it runs destructors for local objects — that's stack unwinding
- Once a handler matches, control jumps there
Here's the trick: steps 2 and 3 read tables baked into the binary rather than running checks along the normal path. That's the entire reason they're "zero cost when not thrown."
The Normal Path: No Overhead
int safe_divide(int a, int b) { if (b == 0) throw std::runtime_error("division by zero"); return a / b;}
int main() { try { int result = safe_divide(10, 2); return result; } catch (const std::exception &e) { return -1; }}The normal path (no exception thrown) compiles to:
main: push rbx mov edi, 10 mov esi, 2 call safe_divide ; Regular call ; If we get here, no exception was thrown pop rbx ret ; Return result in eax
; The try/catch adds ZERO instructions to the normal path!Compare this to what an if-based error handling approach would look like:
; Error-code based approach (always pays the cost):main_with_error_codes: push rbx mov edi, 10 mov esi, 2 call safe_divide test eax, eax ; Check error code - ALWAYS executed js .handle_error ; Branch - ALWAYS evaluated pop rbx ret.handle_error: mov eax, -1 pop rbx retNo test, no js on the exception version's happy path. The error-code version pays for the check on every call, no matter what. For code where errors are rare, exceptions win the throughput contest.
The .eh_frame Section
The compiler generates a .eh_frame section containing DWARF Call Frame Information (CFI). This section describes how to unwind each stack frame:
readelf --debug-dump=frames a.outThe output looks something like:
CIE: length=20, version=1, augmentation="zR" Code alignment factor: 1 Data alignment factor: -8 Return address column: 16 Initial instructions: DW_CFA_def_cfa: r7 (rsp) ofs 8 DW_CFA_offset: r16 (rip) at cfa-8
FDE: length=36, CIE_pointer=0 PC range: 0x401150..0x401185 (safe_divide) Instructions: 0x401151: DW_CFA_advance_loc: 1 DW_CFA_def_cfa_offset: 16 DW_CFA_offset: r6 (rbp) at cfa-16 0x401154: DW_CFA_advance_loc: 3 DW_CFA_def_cfa_register: r6 (rbp)Translation for the unwinder: "For instructions in 0x401150-0x401185, here's how to roll back to the previous stack frame at each PC." The DW_CFA_def_cfa_offset and DW_CFA_offset entries pin down where saved registers sit relative to the stack pointer.
The .gcc_except_table Section
Beyond frame unwinding, the compiler generates a Language-Specific Data Area (LSDA) in .gcc_except_table. This maps code regions to their catch handlers:
LSDA for main: Call site table: [0x10-0x1a]: landing pad at 0x30, action 1 [0x1a-0x25]: no landing pad (no cleanup needed) Action table: action 1: catch type = std::exception, next action = 0 Type table: type 1 = typeinfo for std::exceptionReading that out loud: "If an exception flies while we're between offsets 0x10 and 0x1a (the call safe_divide region), branch to the landing pad at offset 0x30 and check whether the exception is a std::exception."
The Throw Mechanism
When throw executes:
; throw std::runtime_error("division by zero")safe_divide: push rbx cmp esi, 0 jne .normal_path
; Allocate exception object mov edi, 16 ; sizeof(std::runtime_error) call __cxa_allocate_exception ; Allocate from exception pool mov rbx, rax ; Keep the pointer: the constructor returns void
; Construct the exception object (runtime_error("division by zero")) mov rdi, rax ; 'this' for the constructor lea rsi, [rel .LC_msg] ; "division by zero" call _ZNSt13runtime_errorC1EPKc ; runtime_error::runtime_error(const char*)
; Throw! mov rdi, rbx ; Exception object (saved before the call) lea rsi, [rel _ZTISt13runtime_error] ; typeinfo pointer lea rdx, [rel _ZNSt13runtime_errorD1Ev] ; Destructor, run when the exception is freed ; (null only for trivially destructible types like int) call __cxa_throw ; Never returns!The real output also carries a small landing pad that calls __cxa_free_exception if the runtime_error constructor itself throws.
What __cxa_throw does:
- Stashes the exception object and its type info in thread-local storage
- Calls
_Unwind_RaiseExceptionto kick off stack unwinding - The unwinder reads
.eh_frameto unwind each frame in turn - At every frame it checks
.gcc_except_tablefor a matching handler - On a match, control jumps to the landing pad
The list above squashes one detail. The Itanium ABI unwinder used on Linux actually makes two passes. The first only searches, reading each frame's .eh_frame entry and its .gcc_except_table data (the LSDA) without touching anything, and if no handler turns up it calls std::terminate with the stack intact. Only once a handler is found does the second pass go back down, running cleanup pads on the way. Suppose safe_divide throws, its caller process holds a std::string, and main has the catch:
Landing Pads
A landing pad is the entry point for a catch block:
; Landing pad for the catch block in main:.L_landing_pad: ; rax = pointer to the unwinder's header for the exception ; edx = selector (which catch clause matched)
; Call __cxa_begin_catch to mark the exception as being handled mov rdi, rax call __cxa_begin_catch ; rax = pointer to the exception object itself (what e refers to)
; The catch body uses nothing from e, so end the catch straight away call __cxa_end_catch
; Then the catch body's return -1. It comes after the call, because ; eax is caller-saved and __cxa_end_catch is free to trash it mov eax, -1 pop rbx retCleanup Landing Pads (Stack Unwinding)
When a function has local objects with destructors, the compiler generates cleanup landing pads:
void example() { std::string s = "hello"; might_throw(); // If this throws, s must be destroyed}In the listing below, the long symbols are libstdc++'s std::__cxx11::basic_string constructor and destructor, the names GCC has used for std::string since GCC 5 switched to the C++11 string ABI. (Older material shows _ZNSs... names; those belong to the pre-C++11 copy-on-write string.) This is the C++17 spelling GCC 11 and later produce by default.
example: push rbx sub rsp, 48
; Construct s lea rdi, [rsp] lea rsi, [rel .LC_hello] lea rdx, [rsp+47] ; the std::allocator<char> argument call _ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEC1IS3_EEPKcRKS3_ ; std::string::string("hello", allocator)
; Call might_throw call might_throw
; Normal path: destroy s and return lea rdi, [rsp] call _ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEED1Ev ; string::~string() add rsp, 48 pop rbx ret
; Cleanup landing pad: called during stack unwinding.L_cleanup: mov rbx, rax ; Save exception lea rdi, [rsp] call _ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEED1Ev ; Destroy s mov rdi, rbx call _Unwind_Resume ; Continue unwindingThe cleanup landing pad destroys s, then _Unwind_Resume carries on unwinding up the stack. This is the loop that keeps RAII honest under exceptions: the compiler emits cleanup code for every object that needs destroying mid-unwind.
The Cost Breakdown
When nothing is thrown (the usual case):
- Zero extra instructions on the normal path
- The
.eh_frameand.gcc_except_tablesections sit in the binary but never get touched - Cost: a chunkier binary. How much depends heavily on the code, so measure it:
size -A a.outshows the.eh_frameand.gcc_except_tablesizes next to.text
When an exception actually flies (the rare case):
__cxa_allocate_exception: a heap allocation (with an emergency pool ifmallocfails)_Unwind_RaiseException: looks up and parses DWARF tables for every frame, twice (search, then cleanup)- Landing pad execution: destructors run, control transfers
- All in: microseconds rather than nanoseconds. A shallow throw-and-catch typically lands in the low single-digit microseconds on a current desktop CPU, and every extra frame to unwind adds more. The runner at the end of this lesson measures it on real hardware.
noexcept and Its Impact
Marking a function noexcept tells the compiler that no exceptions will escape:
int fast_add(int a, int b) noexcept { return a + b;}With noexcept:
- The compiler skips LSDA entries for this function entirely
- No landing pads needed
- If something does escape anyway,
std::terminatefires on the spot
Smaller binary, more optimisation headroom. Functions reached from noexcept callers can sometimes drop their cleanup landing pads too, when the compiler can prove no exception will ever reach them.
Comparing to C Error Handling
| Aspect | C++ Exceptions | C Error Codes |
|---|---|---|
| Normal path overhead | Zero | Branch + check per call |
| Error path cost | High (microseconds) | Low (just a return) |
| Binary size | Larger (EH tables) | Smaller |
| Composability | Automatic propagation | Manual checking at every level |
| Resource cleanup | Automatic (RAII + unwinding) | Manual (goto cleanup, or error-prone) |
C++ exceptions optimise hard for the no-error case and accept the painful price when one does fly. C error codes spread a small overhead evenly across every call. Which side wins depends on how often errors hit you and how badly you want automatic cleanup.
You don't have to take the "microseconds" in that table on trust. This program runs 200,000 divisions both ways at three failure rates. The runner compiles without optimisation and timings drift between runs, so read the ratios, not the absolute numbers: with no failures the two loops should land close together, and the exception column should balloon as the failure rate climbs.