MiddleDebuggingRareNot answered yet
Can you catch a stack overflow with a C++ try/catch?
This code wraps unbounded recursion in try/catch, expecting to handle the stack overflow gracefully. Instead the program dies and never prints "caught".
void recurse() { recurse(); }
int main() {
try {
recurse();
} catch (...) {
std::cout << "caught\n";
}
}
Identify the bug and explain the cause.
No. Stack overflow is an OS signal (SIGSEGV on Linux, access violation on Windows), not a C++ exception. The runtime cannot unwind without stack space. Windows SEH can intercept the page fault, but that is not portable C++.
- ✗Putting
try { recurse(); } catch (...) {}and expecting it to handle stack overflow - ✗Allocating large arrays on the stack in deeply nested calls
- ✗Mistaking stack overflow for
std::bad_alloc— different mechanism
- →How does Windows SEH differ from C++ exceptions?
- →What's a guard page and how does the OS detect overflow?
Stack overflow does not raise a C++ exception, so catch never sees it. Unbounded recursion hits the guard page — the OS sends SIGSEGV (Linux) or an access violation (Windows), not a throw:
void recurse() { recurse(); } // eats the stack down to the guard page
int main() {
try {
recurse();
} catch (...) { // does NOT fire: this is an OS signal, not an exception
std::cout << "caught\n";
}
} // program dies with SIGSEGV / access violation
The runtime has no stack space left to unwind. Windows SEH can intercept the page fault via __try/__except, but that is not portable C++.