Topic 67 of 91 9. C++ Standard Template Library (STL) Interactive Tutorial

Stack Unwinding in C++: What Happens During Exception Propagation

7 mins read Last updated: 26 Sep 2026 17,179 views

Direct Answer & Core Concept

Stack unwinding is the automatic process where the C++ runtime destroys all local stack objects in reverse order of construction as an exception propagates upward through call frames until a matching catch block is found. This guarantees that RAII-managed resources (memory, mutexes, file handles) are deterministically released.

Detailed Explanation & Mechanics

1. Unwinding Execution Flow:

Architecture Diagram
Call Stack: main() ──► processOrder() ──► chargeCard() [THROW EXCEPTION]
                              │
  ◄── [Stack Unwind Step 1: Destruct local objects in chargeCard()]
  ◄── [Stack Unwind Step 2: Destruct local objects in processOrder()]
  ◄── [Matched Catch Block in main()] ──► Exception Handled!

2. Destructors During Unwinding:

If a destructor throws an exception while stack unwinding is already in progress, std::terminate() is called immediately to prevent catastrophic dual-exception state.

Runnable Code Example: Stack Unwinding in C++

C++20 / C++23
main.cpp
Run Online
#include <iostream>
#include <string>
#include <stdexcept>

class ScopedGuard {
private:
    std::string resourceName;
public:
    explicit ScopedGuard(std::string name) : resourceName(std::move(name)) {
        std::cout << "[Constructed] " << resourceName << "\n";
    }
    ~ScopedGuard() {
        std::cout << "[Destructed / Cleaned] " << resourceName << "\n";
    }
};

void triggerFailure() {
    ScopedGuard guard("Database Transaction");
    std::cout << "Processing transaction... Encountered error!\n";
    throw std::runtime_error("Database connection lost!");
}

int main() {
    std::cout << "Entering main()...\n";
    try {
        triggerFailure();
    } catch (const std::exception& e) {
        std::cout << "Caught exception in main: " << e.what() << "\n";
    }
    std::cout << "Exiting main() gracefully.\n";
    return 0;
}

Common C++ Technical Interview Questions & Answers

Interview Prep
Q

Q: What happens if a destructor throws an exception during stack unwinding?

A: C++ does not allow two active exceptions at once. If a destructor throws an exception during stack unwinding, `std::terminate()` is invoked immediately, aborting the program.
Q

Q: How does RAII leverage stack unwinding?

A: RAII encapsulates resources inside stack-allocated objects. When exceptions occur, stack unwinding automatically triggers destructors, preventing resource and memory leaks without requiring manual cleanup blocks.

Key Takeaways, Modern Best Practices & Idioms

C++ Best Practices & Production Rules

• Ensure all destructors are noexcept to prevent fatal std::terminate() calls during stack unwinding.
• Never rely on manual delete calls after functions that might throw; wrap resources in RAII objects.
• Use std::uncaught_exceptions() if inspection of active exception count is needed during cleanup.
We value your privacy & transparency

OperateTools uses cookies and local storage to ensure basic tool functionality, preserve preferences, and analyze aggregated traffic. We never sell your personal data or index your document files. Learn more in our Privacy Policy.