日期:2014-05-20  浏览次数:20667 次

是return之前执行么?
code=Java]public class Demo {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(new Demo().test());
}
static int test(){
int x = 1;
try
{
return x;

}
finally
{
++x;
}
}
}[[/code]
返回的是1很不解,debug调试还是不解!请教大牛!

------解决方案--------------------
finally 是在return之前执行的
------解决方案--------------------
finally在return执行,但是不会影响return的结果。
------解决方案--------------------
/*这种问题得看字节码才能明白:
static int test();
Code:
 Stack=1, Locals=3, Args_size=0
 0: iconst_1 //常量1压栈
 1: istore_0 //常量1出栈,存储到局部变量0里面,也就是x里面
 2: iload_0 //从局部变量0载入
 3: istore_1 //存到局部变量1里面,变量1就是要返回的值
 4: iinc 0, 1 //局部变量0加1,从这是执行finally里面的++x,可以看出来x再怎么修改对返回结果都没有任何的影响。
 7: iload_1 //从局部变量1载入
 8: ireturn //返回
 9: astore_2
 10: iinc 0, 1
 13: aload_2
 14: athrow
 */

------解决方案--------------------
探讨
/*这种问题得看字节码才能明白:
static int test();
Code:
Stack=1, Locals=3, Args_size=0
0: iconst_1 //常量1压栈
1: istore_0 //常量1出栈,存储到局部变量0里面,也就是x里面
2: iload_0 //从局部变量0载入
3: istore_1 ……

------解决方案--------------------
探讨
public class smallT{
public static void main(String args[]){
smallT t = new smallT();
int b = t.get();
System.out.println(b);
}
public int get(){
try{
return 1 ;
}
finally{
return 2 ;
}
}……