Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 994
Hans-Peter Störr Avatar asked Aug 27 '13 07:08

Hans-Peter Störr


People also ask

Can you catch StackOverflowError?

StackOverflowError is an error which Java doesn't allow to catch, for instance, stack running out of space, as it's one of the most common runtime errors one can encounter.

Why is catching all exceptions bad?

Because when you catch exception you're supposed to handle it properly. And you cannot expect to handle all kind of exceptions in your code. Also when you catch all exceptions, you may get an exception that cannot deal with and prevent code that is upper in the stack to handle it properly.

How do I stop StackOverflowError?

Increase Thread Stack Size (-Xss) Increasing the stack size can be useful, for example, when the program involves calling a large number of methods or using lots of local variables. This will set the thread's stack size to 4 mb which should prevent the JVM from throwing a java. lang. StackOverflowError .

What is a StackOverflowError?

A stack overflow is a type of buffer overflow error that occurs when a computer program tries to use more memory space in the call stack than has been allocated to that stack.


1 Answers

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.

like image 86
Denys Séguret Avatar answered Oct 07 '22 14:10

Denys Séguret