What is the harm in catching a StackOverflowError?

java, stack-overflow

Solution

A stack overflow error doesn't at all mean the memory is exhausted and doesn't make anything inconsistent per se.

But a stack overflow error is usually a bug. You should fix the bug instead of catching the exception. Don't use the exception system to hide bugs.

Even when you know there's a risk of a too deep stack (graph exploration for example), there are better ways to control that than letting the stack explode.

From the Javadoc of the Error superclass :

An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. The ThreadDeath error, though a "normal" condition, is also a subclass of Error because most applications should not try to catch it.

Problem

Just curious. In an answer about catching StackOverflowErrors someone wrote: "Surely there are situations where a stack overflow might leave an application inconsistent just like a memory exhaustion". What's so special about StackOverflowErrors that they threaten to corrupt the application state more than, say, a NullPointerException thrown in case of a Bug? One thing I can think of is that a StackOverflowError can occur in places where normally never ever an exception (or other Throwable, for that matter) is thrown (e.g. a simple getter), so the program probably isn't prepared for this. Are there more diabolical problems?

Original source