如下是运行的结果
public class TryTest {
public static void main(String[] args) {
System.out.println(returnNum());
}
public static Integer returnNum(){
try{
return 2;
}finally {
return 3;
}
}
}
返回的结果是3;
public class TryTest {
public static void main(String[] args) {
System.out.println(returnNum());
}
public static Integer returnNum(){
try{
return 2;
}finally {
System.out.println("hahahh");
}
}
}
返回的结果是 2;
解释说明:
官方的jvm规范说明如下:
If the try clause executes a return, the compiled code does the following:
Saves the return value (if any) in a local variable.
Executes a jsr to the code for the finally clause.
Upon return from the finally clause, returns the value saved in the local variable.
如果try语句里有return,那么代码的行为如下:
1.如果有返回值,就把返回值保存到局部变量中
2.执行jsr指令跳到finally语句里执行
3.执行完finally语句后,返回之前保存在局部变量表里的值
个人解释
也就是先执行try中的语句-> 执行计算return的值存储到局部变量表中 ->跳转到finally ->返回try中的return,即try中return存储在临时变量表中的值,但是如果finally中存在return就直接终止了程序,不会在去返回try中存储在临时变量表中的值