
本教程操作环境:windows7系统、java10版,DELL G3电脑。
1.在 try 语句块之前返回(return)或者抛出异常,finally不会被执行
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | package com.zwwhnly.springbootaction;
public class FinallyTest {
public static void main(String[] args) {
System.out.println( "return value of test():" + test());
}
public static int test() {
int i = 1;
System.out.println( "the previous statement of try block" );
i = i / 0;
try {
System.out.println( "try block" );
return i;
} finally {
System.out.println( "finally block" );
}
}
}
|
只有与 finally 相对应的 try 语句块得到执行的情况下,finally 语句块才会执行。
2.有异常,finally 中的 return会导致提前返回
1 2 3 4 5 6 7 8 9 10 11 12 | public static String test() {
try {
System.out.println( "try" );
throw new Exception();
} catch (Exception e) {
System.out.println( "catch" );
return "return in catch" ;
} finally {
System.out.println( "finally" );
return "return in finally" ;
}
}
|
调用 test() 的结果:
1 2 3 4 | try
catch
finally
return in finally
|
finally 语句块在 try 语句块中的 return 语句之前执行。
以上就是关于java中finally不执行的分析,根据代码运行我们发现,finally在try语句未运行的情况也没有执行,这点需要我们在使用finally时格外注意。