finally代码总会执行
没有异常发生的时候,在try内的代码执行结束后,执行finally。
如果发生了异常并且被catch捕获,则在执行完catch之后执行finally。
如果有异常且未被捕获,则在异常被抛给上层之前执行。
public class Test {
public static void main(String[] args) {
int j = test();
System.out.println(j);
}
public static int test() {
int i = 0;
try {
return i;
} finally {
i = 1;
System.out.println("finally代码被执行");
}
}
}
返回结果为:
finally代码被执行
0
finally里面的代码被执行。但是,虽然给i赋值了1。但返回的值还是0。
所以,即使在try里面使用了return,依然会执行finally。但是finally无法改变返回值。
在执行的过程中, 如果try执行到return,会先将i的值保存在一个临时变量中,等到finally执行完毕之后再将保存的值取出返回。因此finally无法改变最终的返回结果
如果在 return和finally中同时遇到return会怎么样?
public class Test {
public static void main(String[] args) {
int j = test();
System.out.println(j);
}
public static int test(){
int i = 0;
try{
return i;
}finally {
i = 1;
return i;
}
}
}
返回结果为:
1
当遇到try与finally语句中同时含有return语句,会忽略try中return
《JVM规范》中提到:
If the try clause executes a return, the compiled code does the following: 1. Saves the return value (if any) in a local variable. 2. Executes a jsr to the code for the finally clause. 3. Upon return from the finally clause, returns the value saved in the local variable.
大意就是如果在try中包含return的情况下,会先将try中将要return的值先存到一个临时变量中,然后执行finally子句,从finally子句返回时,返回保存在临时变量中的值。