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调试还是不解!请教大牛!
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调试还是不解!请教大牛!
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
*/
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 ;
}
}
}
可是这里怎么又返回的是2!很不解!
执行到return expression;这行的时候,先求取表达式expression的值,将其放入寄存器,然后进入finally,出finally之后,在将之前保存的值取出来返回;而不是执行完finally,然后再去求expression的值。
/*
public int get();
Code:
Stack=1, Locals=3, Args_size=1
0: iconst_1 常量1压栈
1: istore_1 存到局部变量1里面
2: iconst_2 常量2压栈
3: ireturn 返回栈顶元素,那就是2了
4: astore_2
5: iconst_2
6: ireturn
*/