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
2010-03-29 03:59:57
Ah I was trying with a generic exception. Thanks!
stereos
2010-03-29 04:06:29
I agree that finding out what is causing the exception and preventing it would be better though.
Thilo
2010-03-29 04:07:41
@stereos You weren't trying to catch `Exception` were you? `Error` extends `Throwable` directly, not through `Exception`.
Tom Hawtin - tackline
2010-03-29 04:19:38
`catch (XyzError)` is going to end in tears....
skaffman
2010-03-29 12:24:04
+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
2010-03-29 04:04:22
+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
2010-03-29 05:15:08