Search code examples
javaerror-handlingstack-overflow

Code working fine even after StackOverflow - How?


To my understanding following code should print 0 as output because stack is full and it should get out of method immediately.

However when I ran the following code it is printing 100 for first case and prints 1 for second case:

class ErrorAndException {
        public static int callStackOverflow() {
            try {
                callStackOverflow();
                return 100;
            } catch (Error e) {
                System.out.println(e);
                return 0;
            } finally {
            }
        }

        public static void main(String[] args) {
            System.out.println(callStackOverflow());
        }
    }

Case - 2

class ErrorAndException {
            public static int callStackOverflow() {
                try {
                    callStackOverflow();
                    return 100;
                } catch (Error e) {
                    System.out.println(e);
                    return 0;
                } finally {
                           return 1
                }
            }

        public static void main(String[] args) {
            System.out.println(callStackOverflow());
        }
    }

Please help me understand this behavior.


Solution

  • Only the final call to callStackOverflow() (the one in which StackOverflowError is thrown) returns 0. But when it returns, the previous calls to callStackOverflow() all return 100. Your main method prints just the value returned by the initial call to callStackOverflow(), which is 100.

    If you want the 0 to be returned to the main method, callStackOverflow() would have to return the value returned by the recursive call:

    public static int callStackOverflow() {
        try {
            return callStackOverflow();
        } catch (Error e) {
            System.out.println(e);
            return 0;
        } finally {
        }
    }