Stack Unwinding

Introduced in CS247, and used to backtrace Exception Handling.

Notes copied from Exception Handling.

When an exception is raised, control flow steps. We search through the stack upwards looking for a handler for this type of exception. This is called Stack Unwinding. Destructors are run for objects stored on the stack during the process of stack unwinding.

If a handler is found, we jump to that point. If no handler is found, program crashes.

Example of stack unwinding:

void f() {
	throw std::out_of_range{"f threw"};
}
void q() { f();};
void h() {q();};
int main() {
	try { h();}
	catch (std::out_of_range r) {
		cout << r.what();
	}
}
  • Main calls h, h calls q, q calls f, throws, stack unwinding through q, h, jump to catch block in main.