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;
}
}
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;
}
}
我建议一般不要把return 放在finally里面,因为与finally一起用的时候会造成语义混乱,不太清晰,程序不容易维护。
2.当try或catch块中有return语句时,finally块中的语句仍会执行;
3.finally块中的语句是在函数返回前执行的,但函数返回值是在finally块中语句执行前确定的;
4.finally块中不能包含return语句。 楼主可以自己敲下代码验证下、顺便自己理解下。
在转去之前,try中先把要返回的结果存放于不同于i的局部变量中,执行完finally之后在从中取出返回结果
因此,finally中对变量i进行的改变,不会影响返回结果!
你在finally里面对i++,是在ruturn执行之后才做的
并不是finally里的内容不做
但是你return的时候 i是1
但是你整个程序跑完 i是2记住try catch finally
finally里面的内容是一定会执行的 所以都在这里处理资源的释放
面试用的到哦 楼主分拿来把~
// 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]
另外,不存在finally中的i++不会执行的问题,除非之前有导致jvm崩溃的情况,比如System.exit(0);public class Test { static int i = 1; public static void main(String[] args) throws Exception {
System.out.println(test());
System.out.println(i);
} private static int test() { try {
return i;
} catch (Exception e) { } finally {
i++;
}
return 0;
}
}
打印
1
2
而不是到了return再去执行finally,然后回过头来再去运行return 表达式,求当时(finally以后)表达式的值
finally语句中为什么不能含return语句?这样说是否不是很确切?
finally中含有return语句,会有警告,并且,这个函数的返回值取finally语句中的返回值而已,没有意义罢了。鄙人愚见
finally方法应该在return之后执行