Search code examples
javaexceptionstack-overflow

StackOverFlowError Handling and Java Recovery


Can anyone please explain how StackOverFlowError work?

I know endless recursion causes StackOverFlowError, but does any other method gets executed after the stack is full? I have handled the error in catch block. I would like to know how java functions or recovers from the error that has been caught.

Sample code:

public class Test {    
    public static void main(String[] args) {    
        try {
            show();
        } catch(StackOverflowError e) {
            System.out.println(e);
        }    
        System.out.println("After StackOverFlowError");

        display();    
    }

    static void show() {
        show();
    }

    static void display() {
        System.out.println("Hello New Function");
    }    
}

And the output is:

java.lang.StackOverflowError

After StackOverFlowError

Hello New Function


Solution

  • Yes, java recovered from it. When the StackOverflowError is thrown it unwinds the stack through all the show() methods until it gets back to your catch block. At this point only the main() is left on the stack and you could continue executing your program without issue.

    Your call stack will look like:

    main()
       show()
          show()
             show()...
    

    However deep your stack memory allows it to go, when the last show() method gets the exception it throws it to each show method which re-thorws it until it reaches the catch block in your main and the error is printed.