Try-finally block prevents StackOverflowError

后端 未结 6 1921
野趣味
野趣味 2020-12-04 04:54

Take a look at the following two methods:

public static void foo() {
    try {
        foo();
    } finally {
        foo();
    }
}

public static void bar(         


        
6条回答
  •  天涯浪人
    2020-12-04 05:24

    In effort to provide reasonable evidence that this WILL eventually terminate, I offer the following rather meaningless code. Note: Java is NOT my language, by any stretch of the most vivid imagination. I proffer this up only to support Peter's answer, which is the correct answer to the question.

    This attempts to simulate the conditions of what happens when an invoke can NOT happen because it would introduce a stack overflow. It seems to me the hardest thing people are failing to grasp in that the invoke does not happen when it cannot happen.

    public class Main
    {
        public static void main(String[] args)
        {
            try
            {   // invoke foo() with a simulated call depth
                Main.foo(1,5);
            }
            catch(Exception ex)
            {
                System.out.println(ex.toString());
            }
        }
    
        public static void foo(int n, int limit) throws Exception
        {
            try
            {   // simulate a depth limited call stack
                System.out.println(n + " - Try");
                if (n < limit)
                    foo(n+1,limit);
                else
                    throw new Exception("StackOverflow@try("+n+")");
            }
            finally
            {
                System.out.println(n + " - Finally");
                if (n < limit)
                    foo(n+1,limit);
                else
                    throw new Exception("StackOverflow@finally("+n+")");
            }
        }
    }
    

    The output of this little pointless pile of goo is the following, and the actual exception caught may come as a surprise; Oh, and 32 try-calls (2^5), which is entirely expected:

    1 - Try
    2 - Try
    3 - Try
    4 - Try
    5 - Try
    5 - Finally
    4 - Finally
    5 - Try
    5 - Finally
    3 - Finally
    4 - Try
    5 - Try
    5 - Finally
    4 - Finally
    5 - Try
    5 - Finally
    2 - Finally
    3 - Try
    4 - Try
    5 - Try
    5 - Finally
    4 - Finally
    5 - Try
    5 - Finally
    3 - Finally
    4 - Try
    5 - Try
    5 - Finally
    4 - Finally
    5 - Try
    5 - Finally
    1 - Finally
    2 - Try
    3 - Try
    4 - Try
    5 - Try
    5 - Finally
    4 - Finally
    5 - Try
    5 - Finally
    3 - Finally
    4 - Try
    5 - Try
    5 - Finally
    4 - Finally
    5 - Try
    5 - Finally
    2 - Finally
    3 - Try
    4 - Try
    5 - Try
    5 - Finally
    4 - Finally
    5 - Try
    5 - Finally
    3 - Finally
    4 - Try
    5 - Try
    5 - Finally
    4 - Finally
    5 - Try
    5 - Finally
    java.lang.Exception: StackOverflow@finally(5)
    

提交回复
热议问题