Joker
Joker

Reputation: 11146

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.

Upvotes: 2

Views: 75

Answers (2)

Eran
Eran

Reputation: 393771

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 {
    }
}

Upvotes: 6

Cubius
Cubius

Reputation: 101

The final item that causes the overflow will return 0 to the previous instance, but that value is lost as all lower instances just return 100 to one another until the final instance exits returning 100.

Upvotes: 4

Related Questions