Finally in Java 及其机制的讨论

Finally in Java

我们从几个问题开始:

一、finally一定会执行吗?



二、下面语句的执行结果是:

public class FinallyTest {

public static void main(String[] args) {

System.out.println("getValue()返回值为:" + getValue());

}



public static int getValue() {

try {

return 0;

} finally {

return 1;

}

}

}



三、下面语句的执行结果是:

public class FinallyTest {

public static void main(String[] args) {

System.out.println("getValue()返回值为:" + getValue());

}



public static int getValue() {

int i = 1;

try {

return i;

} finally {

i++;

}

}

}




首先,第一个问题,答案是否定的。在try里面执行了System.exit(0);操作finally就不会执行,另外死机、断电都会导致finally不会执行。



对于后面两个问题,我们先看一下摘自《THE Java™ Programming Language, Fourth Edition》By Ken Arnold, James Gosling, David Holmes中的几段话:



a finally clause is always entered with a reason. That reason may be that the try code finished normally, that it executed a control flow statement such as return, or that an exception was thrown in code executed in the TRy block. The reason is remembered when the finally clause exits by falling out the bottom. However, if the finally block creates its own reason to leave by executing a control flow statement (such as break or return) or by throwing an exception, that reason supersedes the original one, and the original reason is forgotten. For example, consider the following code:

try {

// ... do something ...

return 1;

} finally {

return 2;

}


When the TRy block executes its return, the finally block is entered with the "reason" of returning the value 1. However, inside the finally block the value 2 is returned, so the initial intention is forgotten. In fact, if any of the other code in the try block had thrown an exception, the result would still be to return 2. If the finally block did not return a value but simply fell out the bottom, the "return the value 1" reason would be remembered and carried out.



从红色和蓝色字体标注的解释可以看出,当finally中有return语句的时候,try中的return会被抛弃;当finally中没有return语句时,try中return的值会被保存且被返回。



所以,第二个问题的答案是:getValue()返回值为:1



第三个问题的答案是:getValue()返回值为:1

以上内容转自互联网。



以下是对其执行机制的探讨:

首先问一句,为什么会有如上的情况发生?

其实原因在于stack的使用,也就是说,在try, catch, finally语句中,不断将local variable push into stack. 而后在return时只是将其pop out而已,所以在从catch 跳转finally过程中,value已经被保存至stack.如果finally有return 语句,那么将会返回finally保存的新的value,否则会弃掉finally保存的value(add.w #4,SP, 懂汇编的同学应该不陌生这个语句吧?),之后stack上仍然保存着catch语句块保存的value,所以返回值不受finally影响。
总结就是
finally 在这里实际上是一个 subroutine,涉及到入栈出栈,而非简单的call一个method.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值