⚙️Go deeper — read the bookStack unwinding & exception safety— runnable code & full walkthrough →

cpp core · high

Exceptions & Stack Unwinding

A throw unwinds the stack to the nearest matching catch, running destructors (RAII) on the way; no handler -> std::terminate.

🔑 Key line

A throw unwinds the stack to the nearest matching catch, running each frame's destructors (RAII); uncaught anywhere -> std::terminate.

The code

struct Guard {
~Guard();
}; // RAII cleanup in its destructor
void h() {
Guard x;
throw std::runtime_error("boom");
}
void g() {
Guard x;
h();
} // no catch -> unwinds
void f() {
try {
g();
} catch (const std::exception& e) { /* handled here */
}
}
int main() {
f();
}

What this lesson walks through

  1. 01The call stack: main -> f -> g -> h
  2. 02h() throws
  3. 03Unwind h: destructors run
  4. 04Unwind g: destructors run
  5. 05f's catch matches -> stop
  6. 06No handler anywhere -> std::terminate
  7. 07Stack unwinding in one line

main calls f, f calls g, g calls h. Only f wraps its call in a try/catch. Each frame holds local objects (a Guard) whose destructors must run.

See it animated — step by step, at your own pace

Unlock the full interactive walkthrough of Exceptions & Stack Unwinding and 100+ animated C++ interview lessons.

← Previous
The Spaceship Operator <=>
Next →
Exception-Safety Guarantees