免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1263 | 回复: 0

有感java的一个面试题 [复制链接]

论坛徽章:
0
发表于 2008-08-25 11:25 |显示全部楼层
面试题好像是这么问的,在一个异常处理中,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
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP