Skip to content

stack unwinding

serhij.zolotukhin edited this page May 6, 2026 · 3 revisions

Stack unwinding

Under the Hood: The Mechanism

  • Throwing an Exception (__cxa_throw):

    • When you use throw, the compiler calls __cxa_allocate_exception to create the exception object.
    • It then calls __cxa_throw, which initiates the unwinding process by calling a low-level library function like _Unwind_RaiseException.
  • Phase 1: The Search (Finding the Handler)

    • The runtime "walks" up the stack frames. For each frame, it calls a Personality Function (e.g., __gxx_personality_v0 in GCC).
    • The personality function consults the Language Specific Data Area (LSDA)—a metadata table generated by the compiler — to check if the current function has a matching catch block.
    • If no handler is found in any frame, std::terminate() is called immediately.
  • Phase 2: The Cleanup (Unwinding):

    • Once a handler is found, the runtime walks the stack a second time.
    • For every stack frame between the throw site and the catch block, the personality function executes Landing Pads. These are small code blocks that call the destructors for all local automatic objects currently in scope.
    • This ensures RAII (Resource Acquisition Is Initialization) is maintained, preventing memory leaks and releasing system handles.
  • Resuming Execution:

    • After cleaning up the intermediate frames, control is transferred to the matching catch block.
    • Once the catch block finishes, the exception object is deallocated.

Critical Rules

  • No Exceptions in Destructors If a destructor throws another exception during stack unwinding, the runtime cannot handle two active exceptions at once and will call std::terminate() immediately.
  • Performance: In the "happy path" (no exception thrown), this table-driven model has near-zero overhead. However, when an exception is thrown, the unwinding process is computationally expensive because it requires complex table lookups and multiple passes

URLs

https://www.linkedin.com/pulse/exception-handling-c-how-works-under-hood-compilers-sona-badalyan-9co6e/ https://www.youtube.com/watch?v=zBskaBF-Wxo&list=PLaSMZtEVIQLfkQ5rV839mtFUXXNTgiGAx&index=4

My side bar

Clone this wiki locally