Search code examples
javarecursiontry-catchcontrol-flow

finally working in java before stackoverflow with a recursive loop in main()


class exception1 {
    public static void main(String s[]) {
        String v[] = new String[2];
        try {
            main(v);
            System.out.println(5 / 0);

        }
        catch (Exception e) // or (ArithmeticException e)
        {
            System.out.println(e); // Java.lang.ArithmeticException: / by zero

        }
        finally {
            System.out.println("AAAA");
        }
        System.out.println("after finally normal execution");
    }
}

When i run this code, i get countless AAAA's till the stackoverflow error occurs. My question is main(v); calls the main again and yet finally runs :( ? Control flow is somewhat out of my conscience. Is finally so arrogant that it does not even care about main?


Solution

  • First of all, note that StackOverflowError is an Error and not an Exception, so it won't be caught in your catch (Exception e).

    When the StackOverflowError is thrown, that exception will propagate up in the call stack. Each time a stack-frame returns exceptionally, it's finally clause will be executed.

    (The 0/5 expression is not reachable, as you've probably discovered.)

    Here's a picture of what happens:

                                                                   Output
    main()
       main()
           main()
              ...
                 main()
    
                     throw Stack-overflow!
                     Print AAAA before returning exceptionally     AAAA
    
                 rethrow Stack-overflow!
                 Print AAAA before returning exceptionally         AAAA
    
             ...                                                   ...
    
          rethrow Stack-overflow!
          Print AAAA before returning exceptionally                AAAA
    
       rethrow Stack-overflow!
       Print AAAA before returning exceptionally                   AAAA
    
    Uncaught stack-overflow error, print stacktrace.               Exception dump.