1

In the following code, the methods A() and B() are recursively calling each other which causes the StackOverFlow error. After catching this error how does the program continue to its normal flow of executions as the stack is already overflowed and methods C()->D()->E() needs to be put in the calling stack.

package staticTryOuts;

class Test
{
    public static void main(String[] args) {
       try {
        A();
       }catch(Error e) {
           System.out.println(e);
       }
        System.out.println("Hello");
        C();

    }

    static void A() {
        System.out.println("Hello from A");

        B();
    }
    static void B() {
        System.out.println("Hello from B");

        A();
    }
    static void C() {
        System.out.println("Hello World from c.");
        D();
    }
    static void D() {
        System.out.println("Hello world from D");
        E();
    }
    static void E() {
        System.out.println("Hello world from E");

    }
}
Mustapha Belmokhtar
  • 1,231
  • 8
  • 21

1 Answers1

1

The exception being thrown means that it propagates back up the stack, unwinding and clearing stack frames as it goes. By the time the exception makes it back to the catch block at the very top, the stack is basically empty again and has space for the additional stack frames of the method invocations for C, D and E.

Michael
  • 41,989
  • 11
  • 82
  • 128