-5

For each program tell please, would number of method's calls be infinite or final and explain why. These are examples like from Bloch - Java Puzzlers #45

1)

    public static void main(String[] args) 
        {
        try
        {
            main(args);
        }
        catch(StackOverflowError e)
        {
            main(args);
        }
    }

2)

    public static void main(String[] args) 
        {
        try
        {
            main(args);
        }
        catch(StackOverflowError e)
        {
            main(args);
        }
                finally
                {
                        main(args);
                }
    }

There is a point I want to figure out. For example, the depth of Stack in JVM is 1024. We run this program, method Main is called 1024 times then it happens StackOverflowError and we go first time into catch block where method main is called again. So, on which level of depth are we now? 1024? 1023? 1025?? or first stack is filled and then the other stack is created and we start from 0? how it works? Will we even be in block finally in second example?

OxomHuK
  • 205
  • 1
  • 3
  • 7

1 Answers1

2

In the first example, let's treat the whole function as if it doesn't really call itself. Basically, a method call is made, and if the stack overflows, the same method call is made. Obviously, if the first call caused a stack overflow, nothing has changed and the second call causes a stack overflow, which is not caught and results in an exception display. Essentially, if the method it calls overflows the stack, then the number of method calls is finite. Now, because the method calls always calls itself, the method will overflow the stack at some point, and because of what we proved earlier, the number of method calls is finite.

Now that's a nice application of the mathematical way of thinking to computer programming.

As for the second example, it is exactly the same, except because of the finally block, two stack overflows are tolerated before an exception report, and the same logic will lead to the same result.

tbodt
  • 16,609
  • 6
  • 58
  • 83