java中try, finally中return语句的几点心得

来源:互联网 发布:网络语老司机什么意思 编辑:程序博客网 时间:2024/05/17 23:02

 

结果:

 

abc

a:2

aa:1

 

由此可知:在try语句中,在执行return语句时,要返回的结果已经准备好了,就在此时,程序转到finally执行了。

在转去之前,try中先把要返回的结果存放到不同于a的局部变量中去,执行完finally之后,在从中取出返回结果,

因此,即使finally中对变量a进行了改变,但是不会影响返回结果。

 

 

但是,如果在finally子句中最后添加上return a会怎样呢?

 

 

 

结果:

 

abc

a:2

aa:2

 

 

可以看出,当finally中有return语句的时候,try中的return会被抛弃;

 

《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.

 

 

 

总结:

 

1.不管出没出现异常,finally块中的语句都会执行;以下情况除外,:在try里面执行了System.exit(0);操作finally就不会执行,另外死机、断电都会导致finally不会执行。

2.当try或catch块中有return语句时,finally块中的语句仍会执行;

3.finally块中的语句是在return语句执行之后才执行的,即函数返回值是在finally块中语句执行前确定的;

4.finally块中包含return语句时, 会出现警告, 但仍会执行, 此时, try中的return会被抛弃;

 

原创粉丝点击