- 论坛徽章:
- 0
|
面试题好像是这么问的,在一个异常处理中,finally中code是否被执行呢?是在try中的retrun之前还是之后呢?
首先应该有个概念,那就是finally无论是否出现异常均会被执行,这是毫无疑问的,否则就不称之为finally
了,其次,至于finally中的code在try中的return之前还是之后,有兴趣的测试一下下面的代码就知道了。问题很简单,但是出错的人也比较多。
public class ExceptionTest {
public int add() throws Exception{
int a = 1, b = 2;
int result = 0;
try {
result = a + b;
return result=result+1;
} catch (Exception e) {
}
finally {
result = result + 10;
System.out.println(result + " : 这里的值如果是14表明finally在try中 return之后执行,但是执行完之后,又会跳到return中,自己设置断点看吧");
}
return 0;
}
public static void main(String[] args) throws Exception {
ExceptionTest et = new ExceptionTest();
System.out.println(et.add());
}
}
有兴趣的话就进入调试模式看一下,result的值的变化情况。
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.
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/54454/showart_1146414.html |
|