views:

240

answers:

4

Can you try/catch a stack overflow exception in java? It seems to be throwing itself either way. When my procedures overflows, I'd like to "penalize" that value.

+3  A: 

Seems to work:

public class Test {

    public static void main(String[] argv){
        try{
            main(null);
        }
        catch(StackOverflowError e){
            System.err.println("ouch!");
        }
    }

}
Thilo
Ah I was trying with a generic exception. Thanks!
stereos
I agree that finding out what is causing the exception and preventing it would be better though.
Thilo
@stereos You weren't trying to catch `Exception` were you? `Error` extends `Throwable` directly, not through `Exception`.
Tom Hawtin - tackline
`catch (XyzError)` is going to end in tears....
skaffman
+8  A: 

If you are getting a stack overflow, you are likely attempting infinite recursion or are severely abusing function invocations. Perhaps you might consider making some of your procedures iterative instead of recursive or double-check that you have a correct base case in your recursive procedure. Catching a stack overflow exception is a bad idea; you are treating the symptoms without addressing the underlying cause.

Michael Aaron Safyan
+1  A: 

I agree with Michael - StackOverflowException is a signal that something went very wrong. Swallowing it is not a good idea. The best course of action is to fix the root cause of this error.

Slava Imeshev
A: 

You have to catch an Error, not the Exception

Daniel