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 -> unwindsvoid f() { try { g(); } catch (const std::exception& e) { /* handled here */ }}int main() { f();}What this lesson walks through
- 01The call stack: main -> f -> g -> h
- 02h() throws
- 03Unwind h: destructors run
- 04Unwind g: destructors run
- 05f's catch matches -> stop
- 06No handler anywhere -> std::terminate
- 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.