try/catch中有return,finally也有return,Sun又说了finally中的代码必须执行,
如果执行finally中的return, try/catch中的return 还执行吗?
如果所有的return都执行,执行的先后顺序是怎样,最后实际又返回了哪个return后面的值呢?
来试试:
------------------------------------------------------------------------------------------------------
public class Main {
public static void main(String... args) {
System.out.println(tcf());
}
public static int tcf(){
try{
System.out.println("try");
throw new Exception();
}
catch (Exception e) {
System.out.println("catch");
return one(); //注意one方法中的输出
}
finally{
System.out.println("finally");
return two();
}
}
public static int one(){
System.out.println("one");
return 1;
}
public static int two(){
System.out.println("two");
return 2;
}
}
-----------------------------------------------------------------------------------
就得到下面的结果
-----------------------------------------------------------------------------------
try
catch
one
finally
two
2
-----------------------------------------------------------------------------------
结论是:
先执行了return one();,然后依据语法规定又不得不执行finally block,于是又执行了return two();
如果你学过编译原理,你可以把“return one();”理解为被编译成了一下几行:
1 returnValue = one();
2 if(没有紧接着的finally语句块)
3 goto 调用本方法的地方;
4 else
5 执行finally语句块
执行了两个return 后,相当于给returnValue 赋了两次值,所以returnValue等于后一个值
那下面这段代码的返回值和输出结果是什么呢?如果你理解了我的意思,很容易得出结论
-----------------------------------------------------------------------------------
try{
try{
return one();
}finally{
return two();
}
}finally{
return three();
}