Dr. Hans-Peter Störr
Dr. Hans-Peter Störr

Reputation: 25976

What is the harm in catching a StackOverflowError?

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?

Upvotes: 10

Views: 530

Answers (2)

Denys Séguret
Denys Séguret

Reputation: 382150

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.

Upvotes: 11

JavaDM
JavaDM

Reputation: 851

An error is a serious problem that should not be caught therefore: also do not catch the super class (Throwable) if a method throws an error you do not have to declare a throws-clause

The behavior of an application is often not predictable after an error - errors indicate an abnormal condition

So if an StackOverflowError has been thrown, the application reached the maximum of stack-places for now. You could recheck your application for starting e.g. the garbage collector sooner.

Upvotes: 0

Related Questions