Try-finally block prevents StackOverflowError

后端 未结 6 1909
野趣味
野趣味 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:16

    Try running the following code:

        try {
            throw new Exception("TEST!");
        } finally {
            System.out.println("Finally");
        }
    

    You will find that the finally block executes before throwing an Exception up to the level above it. (Output:

    Finally

    Exception in thread "main" java.lang.Exception: TEST! at test.main(test.java:6)

    This makes sense, as finally is called right before exiting the method. This means, however, that once you get that first StackOverflowError, it will try to throw it, but the finally must execute first, so it runs foo() again, which gets another stack overflow, and as such runs finally again. This keeps happening forever, so the exception is never actually printed.

    In your bar method however, as soon as the exception occurs, it is just thrown straight up to the level above, and will be printed

提交回复
热议问题