Brief overview
What is the C++ exception mechanism?
C++ exceptions look simple at the language level, but the runtime
behavior is much more involved. A single throw raises
several questions:
- How does the runtime find the matching
catch, especially across deep call stacks? - Since
throwchanges control flow, are stack objects inside thetryblock still destroyed correctly? - If the call chain mixes different languages, such as
C -> C++ -> C -> C++, can exception handling still work when plain C does not support exceptions? - What kinds of exceptions cannot be caught by ordinary
catchblocks?
1 | struct RAII { |
The rest of the article answers these questions by following the runtime source path.
Design idea
Exception handling exists in many high-level languages. It can stop the current function immediately and hand control to a function that can actually handle the error.
Bjarne Stroustrup explained the basic motivation in The C++ Programming Language: a library author can detect a runtime error, but usually does not know how to handle it because that depends on the application. The application author knows how to handle it, but does not know when it will occur. Exceptions solve exactly that problem by separating error detection from error handling.
The core idea is therefore not just “throwing an exception”, but finding the right handling path while cleaning up the execution context along the way.
Which implementation mechanisms exist?
There have been several C++ exception implementations over time.
- SJLJ is older and simple, but not very efficient.
- EHABI is mainly used on ARM32 and is tightly coupled to that architecture.
- DWARF CFI is the most widely used mechanism today. It offers a good balance of performance and capability, and is the focus of this article.
- Compact Unwind is an Apple-specific optimization. It only supports simple stack unwinding; for complex cases, the system falls back to DWARF CFI.
Layered model
The Itanium C++ ABI splits exception handling into two layers:
Level 1, the foundational ABI, is the cross-platform
unwind library. Its APIs are usually Unwind*, and common
implementations include libgcc and libunwind.
- It captures and restores execution context and supports stack unwinding.
- It exposes call stack information during exception handling and debugging.
Level 2, the C++ ABI, provides the C++ standard
library ABI support, especially for exceptions and RTTI. Its APIs
usually start with __cxa_*, and common implementations
include libsupc++ and libc++abi.
- It implements key pieces such as
__cxa_throw,__cxa_rethrow, and__gxx_personality_v0. - It also provides dynamic type information support, such as
typeinfoanddynamic_cast.
The Itanium C++ ABI is usually discussed in four areas. This article focuses on the exception-handling part.
Exception overview
The figure summarizes the full flow: __cxa_throw,
_Unwind_RaiseException, unwind_phase1,
unwind_phase2, landingpad, and the supporting
metadata such as eh_frame, unw_proc_info_t,
CIE, FDE, exception table, and
call site table.
We can split the mechanism into three stages:
- Throw the exception.
- Unwind the stack.
- Catch and handle the exception.
The source code in the article is trimmed for focus, and the discussion mainly targets ARM64.
Throwing an exception
__cxa_allocate_exception
When user code executes throw, control first reaches
__cxa_allocate_exception. This function allocates a piece
of memory that contains an exception header, used by the
C++ ABI, followed by the actual user-thrown object.
1 | void *__cxa_allocate_exception(size_t thrown_size) throw() { |
This looks like a simple allocation, but the constraints are subtle. Allocating on the stack is a bad fit because the stack is precisely what will be unwound. Allocating on the heap can also fail because an exception may need to be thrown under memory pressure. Static allocation is not enough either because the operation must be thread-safe. Most implementations therefore allocate from thread-local storage, and use an emergency storage area when ordinary allocation fails.
__cxa_throw
After the memory is ready, execution enters __cxa_throw.
It initializes the __cxa_exception structure, pushes the
exception into the thread-local exception-management stack
__cxa_eh_globals, and finally calls
_Unwind_RaiseException.
1 | void __cxa_throw(void *thrown_object, std::type_info *tinfo, |
The layout of __cxa_exception,
_Unwind_Exception, and the actual thrown object matters
because the runtime frequently converts between those pointers. For
example, from an _Unwind_Exception *, libc++abi can recover
the surrounding __cxa_exception *.
1 | struct __cxa_exception { |
1 | struct _Unwind_Exception { |
The thread-local __cxa_eh_globals stores the top
exception and the number of uncaught exceptions:
1 | struct __cxa_eh_globals { |
Every new exception links its header to the current top exception
through nextException, then updates
caughtExceptions. Exception handling therefore behaves like
a stack: the newest exception is handled first.
__cxa_begin_catch decreases the uncaught count and pushes
the current cxa_exception; __cxa_end_catch
pops it back out.
Stack unwinding
_Unwind_RaiseException
_Unwind_RaiseException is the entry point into
libunwind. It uses the classic two-phase unwinding model:
unwind_phase1 and unwind_phase2.
1 | _Unwind_Reason_Code _Unwind_RaiseException(_Unwind_Exception *exception_object) { |
unwind_phase1, the search phase, walks the stack looking
for an exception handler. If no handler is found, libunwind returns
_URC_END_OF_STACK; the caller decides how to terminate.
unwind_phase2, the cleanup phase, walks frames again,
runs cleanups, destroys out-of-scope objects, and eventually transfers
control to the handler frame. If phase 1 fails, phase 2 never runs,
which means stack objects do not get destructed by the exception
path.
unwind_phase1
The core loop in phase 1 repeatedly steps to the next frame, fetches frame metadata, and asks the frame’s personality routine whether this frame wants to stop the unwind.
1 | static _Unwind_Reason_Code |
The search itself also performs type matching through RTTI, so a call
chain with many catch clauses can make phase 1 more
expensive.
unwind_phase2
Phase 2 looks very similar, but its purpose is different. It walks
the stack again and tells each personality routine that cleanup is now
happening. When the stack pointer equals the value saved in
exception_object->private_2, the current frame is the
handler frame found during phase 1.
1 | static _Unwind_Reason_Code |
In short, phase 2:
- Calls
__unw_step_stage2to move to the previous frame. - Reads the current stack pointer and frame metadata.
- Invokes the personality routine with
_UA_CLEANUP_PHASE. - If the personality routine returns
_URC_INSTALL_CONTEXT, libunwind resumes execution at the generated landing pad.
Others
__unw_step
Both phases rely on __unw_step or
__unw_step_stage2 to move one frame upward. A single step
needs to solve two problems:
- Restore callee-saved registers.
- Correctly set
pc,lr,fp, andsp.
1 | int __unw_step(unw_cursor_t *cursor) { |
On DWARF CFI, the actual logic eventually reaches
stepWithDwarfFDE, and then
DwarfInstructions::stepWithDwarf. That function decodes CIE
and FDE, interprets DWARF instructions, calculates the CFA, restores
registers from the previous frame, and sets IP to the return
address.
1 | int stepWithDwarfFDE(bool stage2) { |
1 | // DwarfInstructions.hpp in libunwind |
The CFA, Canonical Frame Address, is the caller’s stack pointer value when entering the current function. In practice, libunwind calculates the CFA, reads saved registers from locations relative to it, sets the previous IP, and then replaces the in-memory register snapshot. These are not hardware registers yet; they are a saved register state that will later be loaded into real registers when resuming.
1 | class _LIBUNWIND_HIDDEN Registers_arm64 { |
__unw_get_proc_info
__unw_get_proc_info fetches unw_proc_info_t
for the current frame. This structure contains the function range, LSDA
address, personality routine pointer, compact unwind format, and the
DWARF unwind-info address.
1 | struct unw_proc_info_t { |
The information is obtained from CIE and FDE:
1 | _LIBUNWIND_HIDDEN int __unw_get_proc_info(unw_cursor_t *cursor, unw_proc_info_t *info) { |
1 | bool UnwindCursor<A, R>::getInfoFromFdeCie( |
Catching and handling exceptions
Personality routine
During both phases, libunwind obtains the personality routine with
get_handler_function:
1 | static _Unwind_Personality_Fn get_handler_function(unw_proc_info_t *frameInfo) { |
The personality routine is a callback. This is the key reason libunwind can remain language-independent: C++, Objective-C, SJLJ, Windows SEH, and other systems can provide different personalities.
1 | typedef _Unwind_Reason_Code (*_Unwind_Personality_Fn)(int, _Unwind_Action, |
Common examples:
__gxx_personality_v0: C++__gxx_personality_sj0: SJLJ__gcc_personality_v0: C with-fexceptionsand cleanup attributes__CxxFrameHandler3: Windows MSVC__gxx_personality_seh0: MinGW-w64 SEH exceptions__objc_personality_v0: Objective-C on macOS
For libc++abi, the personality routine is
__gxx_personality_v0. It receives the exception context,
the exception object, and the current frame’s exception table
information.
1 | _Unwind_Reason_Code __gxx_personality_v0( |
During the search phase, it scans LSDA to find exception-handling
information for the current frame. If no match is found, it returns
_URC_CONTINUE_UNWIND; if a handler is found, it caches the
result inside __cxa_exception for phase 2.
During the cleanup phase, there are two paths. If phase 1 already cached a handler result, the personality routine can reuse it directly. Otherwise, it scans LSDA again and updates the context from the new result.
When a landing pad is selected, set_registers sets the
exception object into argument register 0, the type index into argument
register 1, and the instruction pointer to the landing-pad address.
1 | static void set_registers(_Unwind_Exception* unwind_exception, |
After __gxx_personality_v0 returns
_URC_INSTALL_CONTEXT, unwind_phase2 calls
__unw_phase2_resume. On ARM64 this eventually loads the
prepared register snapshot and jumps to the landing pad.
1 | DEFINE_LIBUNWIND_FUNCTION(__libunwind_Registers_arm64_jumpto) |
At the jump moment, a typical stack looks like this:
1 | frame #0: libunwind.1.dylib`__libunwind_Registers_arm64_jumpto |
Landing pad
Every time unwind_phase2 steps through a frame, it may
jump into a landing pad. There are three common landing-pad
patterns:
- cleanup clause: calls destructors for out-of-scope
variables, then calls
_Unwind_Resumeto return tounwind_phase2. - catch clause: calls destructors, enters
__cxa_begin_catch, runs the catch handler, and then calls__cxa_end_catch. - rethrow: calls
__cxa_end_catch, destroys objects inside the catch clause, then calls_Unwind_Resumeto continue unwinding.
The rethrow case is easy to misunderstand. It means the previous exception has already been caught and is being thrown again while still inside the current frame. Before the new unwind proceeds, the runtime must clean up the current catch block correctly.
CFI, CIE, and FDE
CFI, Call Frame Information, is the DWARF data and instruction set that describes how to restore a stack frame to its caller. It records how the return address and caller registers are saved, allowing the unwinder to walk the stack.
CFI has two important structures: CIE and FDE.
- CIE stores shared entry information, including personality routine and augmentation data. A CIE can be shared by multiple functions.
- FDE stores unwind information for one function. The most important part is its CFI instruction sequence, which tells the unwinder how to recover register values at each address inside that function.
1 | struct CIE_Info { |
1 | struct FDE_Info { |
Some common CFI directives look like this:
1 | .cfi_startproc |
LSDA
Earlier we said that the personality routine scans
eh_frame to obtain LSDA. LSDA, Language Specific Data Area,
is the per-function language-specific exception table. It records:
- Which instruction ranges may throw.
- Which landing pad should handle a range.
- Which typeinfo pointer should be used for matching.
The instruction range decides whether the current throw belongs to
this frame. The typeinfo match decides whether the frame’s
catch can handle this exception. If both match, control can
transfer to the landing pad.
LSDA structure
LSDA mainly contains four parts:
- Header
- Call Site Table
- Action Table
- Type Table
The Action Table has three kinds of actionType:
The Type Table is split into two regions. Entries above the dividing line are exception types, stored in reverse order. Entries below it are exception-specification indexes, which were removed in C++17.
Real LSDA in assembly looks like this:
LSDA parsing
The core parser is scan_eh_tab. Its job is to parse
LSDA, iterate the Call Site Table, obtain the Action Table index, read
ttypeIndex from the Action Table, and then use
ttypeIndex to find a typeinfo entry in the Type Table.
Finally it checks whether the thrown type matches the catch type.
1 | static void scan_eh_tab(scan_results &results, _Unwind_Action actions, |
The parsing flow is:
- Get the LSDA pointer with
_Unwind_GetLanguageSpecificData(context). - Parse the LSDA header:
lpStartEncoding,ttypeEncoding,callSiteEncoding, andclassInfoOffset. - Parse the Call Site Table. Each entry records
start,length,landingPad, andactionEntry. - Parse the linked list of action entries. Each entry contains
ttypeIndexand the offset to the next action. - Use the Type Table to get
typeinfo, then callcatchType->can_catch(excpType, adjustedPtr).
RTTI
RTTI is the last critical piece. Exception matching depends on runtime type comparison.
Defects of type_info
std::type_info is the standard RTTI interface. It can
represent the dynamic type of an object and expose basic information
such as the type name, but by itself it does not describe type
relationships. It cannot answer questions such as:
- Whether two classes form an inheritance relationship.
- Whether that inheritance is public or virtual.
- How to adjust a base-class subobject pointer so it points to the derived object.
1 | class type_info { |
So each ABI extends RTTI beyond the standard surface.
Class-related
type_info
Possible std::type_info subtypes include:
1 | abi::__fundamental_type_info |
For class types, libc++abi mainly uses:
1 | class __shim_type_info : public std::type_info { |
Their meanings are:
__class_type_info: a class with no base class.__si_class_type_info: a class with exactly one direct, public, non-virtual base class.__vmi_class_type_info: all other class cases, including multiple inheritance and virtual inheritance.
These three class type-info structures share can_catch,
so the interesting logic starts in
__class_type_info::can_catch.
1 | bool __class_type_info::can_catch(const __shim_type_info* thrown_type, |
bullet1: is_equal
The first check is direct type equality:
1 | static inline bool is_equal(const std::type_info* x, |
std::type_info::operator== is backed by ABI-specific
implementations:
1 | class type_info { |
There are three possible __impl variants:
__unique_impl::__eq
1 | struct __unique_impl : __string_impl_base { |
Under compilers that follow the Itanium ABI, there is usually only one RTTI copy for a given type, so comparing the type-name address is enough. There is no need for string comparison, which improves performance and keeps the logic simple.
__non_unique_impl::__eq
1 | struct __non_unique_impl : __string_impl_base { |
For various reasons, the linker may fail to merge all RTTI copies for
a type (llvm.org/PR37398). In that case, two
type_info values are considered equal if their addresses
are equal or their name strings are equal.
__non_unique_arm_rtti_bit_impl::__eq
1 | struct __non_unique_arm_rtti_bit_impl { |
The Apple ARM64 design avoids weak-symbol problems. Hidden typeinfo can still be deduplicated within a linked image, while separate images can keep separate RTTI copies without being unexpectedly redirected.
bullet2: __dynamic_cast_info
If the types are not directly equal, the runtime must check
inheritance. It uses dynamic_cast-style metadata and
__dynamic_cast_info to verify whether
thrown_type publicly and unambiguously derives from the
catch type.
1 | __dynamic_cast_info info = |
The traversal differs for ordinary classes, single inheritance, multiple inheritance, and virtual inheritance:
1 | void __class_type_info::has_unambiguous_public_base( |
This is closely tied to the C++ object model:
For a better intuition, the inheritance-layout diagrams from Deep Dive into C++ Polymorphism 2: Inheritance are useful:
Summary
This article followed the C++ exception path from the source-code
level: throwing, two-phase unwinding, frame stepping, personality
routines, LSDA parsing, landing-pad selection, and RTTI-based type
matching. The key takeaway is that throw is not a direct
jump to catch. It is a cooperation between
compiler-generated metadata and runtime stack-unwinding logic.
QA
A tricky C++ exception debugging case
From real-world debugging posts, type_info mismatch is
one of the most common causes of failed catches. The root cause is often
duplicated RTTI.
Case 1: Shocking! The try-catch statement stopped working?
The failure came from an Objective-C component that used exceptions
while RTTI was disabled. To preserve exception type information, the
compiler emitted another copy of type_info. Because the
component was linked statically, that copy ended up in the main binary.
The main binary and libc++ then contained identically named but distinct
type_info objects, and can_catch failed to
match them.
In iOS projects, CocoaPods usually builds components as separate
targets. If any target disables RTTI, it may affect exception handling
in the host app. If RTTI is disabled, exception handling should usually
be disabled too, namely -fno-rtti together with
-fno-exceptions.
Case 2: A satisfying debugging story about C++ standard-library exceptions
On Android, ANDROID_STL defaults to c++_static
in CMake. The C++ standard library is then linked into the application’s
.so, leaving the relevant type_info symbols
local to that image, and can_catch may fail across library
boundaries. Switching to c++_shared, or exporting
typeinfo and vtable symbols so that they
resolve through libc++.so or libstdc++.so, can
solve the issue.
Is two-phase unwinding necessary?
Not strictly. The Itanium C++ ABI Exception Handling document explains that the two-phase model is not required for C++ semantics, but it provides benefits. In particular, phase 1 allows an exception system to dismiss or handle an exception before the stack has actually been unwound. C++ does not support resumptive exception handling, but other languages do, and the two-phase design lets C++ coexist with those languages on the same stack.
Is there a lower-cost way to understand exceptions?
I strongly recommend the C++
Exceptions under the hood series. It builds a minimal
MyCxxABI on top of libunwind, which is a great way to debug
and understand the mechanism. The original code is old and may not
compile directly now, so I also kept a local reference package here:
[test.zip](/2026/03/07/从源码看 C++ 异常/test.zip)
Foreign Exception vs Native Exception
Can code compiled by clang++ catch an exception thrown
by code compiled by g++?
[gcc_clang_abi_test.zip](/2026/03/07/从源码看 C++ 异常/gcc_clang_abi_test.zip)
I tested two mixed-compiler C++ files. The result:
1 | === GCC and Clang mixed exception-handling demo === |
Why are C++ destructors forbidden from throwing?
A throwing destructor can create a double-exception situation:
first exception is thrown -> stack unwinding starts -> obj destructor runs -> obj destructor throws a second exception -> now two active exceptions exist, and the runtime cannot proceed safely.
So destructors should not let exceptions escape. If cleanup may fail, catch the exception inside the destructor and either swallow it deliberately or terminate explicitly.
Does Objective-C exception handling work the same way?
Objective-C exception handling is very close to the C++ mechanism. Many Objective-C exception APIs wrap the same C++ exception machinery.
1 | void objc_exception_throw(id obj) |
What about Swift exceptions?
Swift’s error model is based on try, catch,
throws, and throw. A throws
function declares that it may return an error, and throw
produces that error at runtime.
The important difference is that Swift errors are values, not
stack-unwinding control-flow interruptions. Conceptually it is closer to
Result<T, E> or Objective-C’s NSError
pattern than to C++ exceptions. In pure Swift projects, relying on
Objective-C exceptions should be avoided; in mixed projects, it should
be handled with extra care.
Is Java exception handling similar?
At the language level, both Java and C++ have try-catch,
exception propagation, and stack unwinding. But their implementation
models are different. C++ heavily depends on ABI-level metadata, LSDA,
RTTI, and compiler-generated landing pads. Java exceptions are managed
by the VM, where the runtime owns the stack metadata and exception
tables.
How should we treat C++ exceptions?
Different ecosystems have made different tradeoffs.
Google’s C++ style guide says not to use exceptions, but it also says the reason is largely historical: too much existing Google C++ code was not prepared for exception safety.
Qt also avoids exceptions. Its documentation mentions historical and practical reasons, including binary-size cost. Turning on exceptions can increase library size significantly.
Modern languages have also been rethinking error handling. Go and
Rust both return to the idea of “errors as values”; Rust’s
Result<T, E> makes error flow explicit and
composable.
My personal view is that C++ exceptions are neither magic nor evil. They are a powerful ABI feature with real cost and real failure modes. In codebases that choose to use them, exception safety and RTTI consistency must be treated as part of the engineering contract.
References
- Itanium C++ ABI
- C++ exception implementation principle and source analysis
- Itanium C++ ABI: Exception Handling
- LLVM Exception Handling
- C++ exception handling mechanism
- C++ exception handling
- C++ exception handling ABI
- libc++abi Specification
- Implementing exception catching and coroutine behavior with setjmp and longjmp in C
- dynamic_cast implementation analysis and performance optimization
- Understanding the C++ ABI
- Shocking! The try-catch statement stopped working?
- C++ Exceptions under the hood
- Stack unwinding
- Exploiting the Hard-Working DWARF
- Linux .eh_frame section and libunwind
- CFI directives
- [libc++abi] Improve performance of __dynamic_cast
- C++ object model practice notes
- Deep Dive into C++ Polymorphism 2: Inheritance
- what-is-the-vtt-for-a-class