在这里,我在上面提供的示例中添加了更多内容,可能会在将来对某人有所帮助,并希望避免一些混乱。
让我们开始吧。
其实还是要看程序的流控。这意味着如果程序的编写方式是,如果您的代码正在处理 try 块中抛出的异常,并且如果您在 catch 块中处理它们,那么 finally 块之后的代码将在 finally 块中的代码之后执行块。
示例1:这里的异常已经被处理,因此finally之后的代码,块执行。
public class TestFinally {
public static void main(String[] args) throws Exception {
try {
boolean flag = true;
if (flag) {
throw new Exception("hello");
}
}
catch(Exception e){
System.out.println("catch will get printed");
}
finally {
System.out.println("this will get printed");
}
System.out.println("this won't show up");
}
}
结果:
catch will get printed
this will get printed
this won't show up
示例 2: 如果 try 块中的异常没有按照上面 Nathan 的说明正确处理,则 finally 块之后的代码不会被执行。
public class TestFinally {
public static void main(String[] args) throws Exception {
try {
boolean flag = true;
if (flag) {
throw new Exception("hello");
}
}
// not handling the exception thrown above
/*catch(Exception e){
System.out.println("catch will get printed");
}*/
finally {
System.out.println("this will get printed");
}
System.out.println("this won't show up");
}
}
结果:
this will get printed
Exception in thread "main" java.lang.Exception: hello
at com.test.TestFinally.main(TestFinally.java:36)
因此,总而言之,finally 块内的代码总是会执行,除非在某些情况下线程在 finally 块之前已停止或终止,或者以防在 try 块中写入任何退出程序。而 finally 之后的代码依赖于 try-catch-finally 块中编写的代码以及异常处理。