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!Stack Unwinding in C++: What Happens During Exception Propagation
Direct Answer & Core Concept
Detailed Explanation & Mechanics
1. Unwinding Execution Flow:
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#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 PrepQ: What happens if a destructor throws an exception during stack unwinding?
Q: How does RAII leverage stack unwinding?
Key Takeaways, Modern Best Practices & Idioms
C++ Best Practices & Production Rules
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.