3

This question extends from Try-finally block prevents StackOverflowError.

If I add a catch block, why catch block codes never runs?

public static void foo() {
    try {
        foo();
    } catch(StackOverflowError e) {       
       System.exit(1); // or System.err.println("ouch!"); whatever
    } finally {
        foo();
    }
}

I refer to JLS Chapter 11.1.3 - Asynchronous Exceptions - is it the reason cause catch block have no chance to run?

Community
  • 1
  • 1
atealxt
  • 186
  • 1
  • 6
  • How can `StackOverflowError.` happen here? – Ruchira Gayan Ranaweera Jul 10 '15 at 09:16
  • 2
    "it's not working" doesn't describe the behaviour you expect or the behaviour you observe. – Jon Skeet Jul 10 '15 at 09:17
  • Thanks I edit the question to write whole method and some description – atealxt Jul 10 '15 at 09:19
  • 4
    Because "it will take a really, really long time" to throw the StackOverflowError. http://stackoverflow.com/a/12439093/1048340 – Jared Rummler Jul 10 '15 at 10:37
  • As per your linked question, the `finally` is run before the exception is thrown, so it recurses through `foo()` for a very long time before the first exception is thrown. – Evan Knowles Jul 10 '15 at 10:42
  • @jared-rummler In the link's replying suppose we have max depth 5 so the first "foo() which fails to call foo()" should reach very quickly, my question is why it is not able be catch by a proper catch block. – atealxt Jul 13 '15 at 06:58
  • @evan-knowles That's not true. The first StackOverflowError will be throw just follows the first finally completes abruptly, if max depth is 5 the stack will fluctuate in 4 and 5 during whole process. I believe it is but can't prove it yet. – atealxt Jul 13 '15 at 06:58

0 Answers0