finally块内的代码和finally块后的代码有什么区别?

pet*_*ete 3 java finally try-catch try-catch-finally

我想知道finally块内的代码和finally块后的代码有什么区别

Nat*_*hes 7

一个小的测试程序显示出差异:

public class FinallyTest {

    public static void main(String[] args) throws Exception {
        try {
            boolean flag = true;
            if (flag) {
                throw new Exception("hello");
            }
        } finally {
            System.out.println("this will get printed");
        }
        System.out.println("this won't show up");
    }
}
Run Code Online (Sandbox Code Playgroud)

此打印

this will get printed
Exception in thread "main" java.lang.Exception: hello
    at snippet.FinallyTest.main(FinallyTest.java:7)
Run Code Online (Sandbox Code Playgroud)

一旦引发了异常,该线程将执行的唯一操作(直到捕获到异常)才是finally块(该异常将留下一个finally所属的try块)。