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

try catch finally执行的疑问
public class TestTry {
public static void main(String[] args) {
System.out.println(test());//为什么打印 1
}

private static int test()
{
int i = 1;
try {
return i;
} catch (Exception e) {


}
finally
{
i++;
}
return 0;
}
}

------解决方案--------------------
我受不了了。。。1#真无敌了。。。
你在finally里面对i++,是在ruturn执行之后才做的
并不是finally里的内容不做
但是你return的时候 i是1
但是你整个程序跑完 i是2

记住try catch finally
finally里面的内容是一定会执行的 所以都在这里处理资源的释放
面试用的到哦 楼主分拿来把~
------解决方案--------------------
Java code

  // Method descriptor #28 ()I
  // Stack: 1, Locals: 4
  private static int test();
     0  iconst_1 // 常量1
     1  istore_0 [i] // 存入寄存器0,即i,以上两行对应 int i = 1
     2  iload_0 [i] // 读取寄存器0,即i
     3  istore_3 // 存入寄存器3,用以之后的return。以上两行对应return i这里,但是仅仅是finally执行之前的部分
     4  iinc 0 1 [i] // 进入finally,对寄存器0,即i,进行+1操作,对应i++
     7  iload_3 // 重新进入return代码部分,读取寄存器3,即刚才存放的用以return的值
     8  ireturn // return
     9  astore_1
    10  iinc 0 1 [i]
    13  goto 22
    16  astore_2
    17  iinc 0 1 [i]
    20  aload_2
    21  athrow
    22  iconst_0
    23  ireturn
      Exception Table:
        [pc: 2, pc: 4] -> 9 when : java.lang.Exception
        [pc: 2, pc: 4] -> 16 when : any
        [pc: 9, pc: 10] -> 16 when : any
      Line numbers:
        [pc: 0, line: 17]
        [pc: 2, line: 19]
        [pc: 4, line: 23]
        [pc: 7, line: 19]
        [pc: 9, line: 20]
        [pc: 10, line: 23]
        [pc: 16, line: 22]
        [pc: 17, line: 23]
        [pc: 20, line: 24]
        [pc: 22, line: 25]
      Local variable table:
        [pc: 2, pc: 24] local: i index: 0 type: int
      Stack map table: number of frames 3
        [pc: 9, full, stack: {java.lang.Exception}, locals: {int}]
        [pc: 16, same_locals_1_stack_item, stack: {java.lang.Throwable}]
        [pc: 22, same]

------解决方案--------------------
这段代码是先执行i=1;给i赋值1后,i的值存在内存中的,然后finnaly块中i++,这时候打印会是2因为i++了,但是return返回的值还是先前存在内存中的1。
------解决方案--------------------
探讨
嗯,但由于i是声明在方法里面的自动变量,在i++之后就会被丢弃,所以i++实际上浪费了计算资源。还是建议不要这样写了。