前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java 异常丢失及finally子句

Java 异常丢失及finally子句

作者头像
Dylan Liu
发布2019-07-01 11:29:26
4840
发布2019-07-01 11:29:26
举报
文章被收录于专栏:dylanliudylanliu

几天前在Stack overflow上看到一个题:

I have a small theoretical problem with try-catch constructions.

I took a practical exam yesterday about Java and I don't understand following example:

代码语言:javascript
复制
try {
    try {
        System.out.print("A");
        throw new Exception("1");
    } catch (Exception e) {
        System.out.print("B");
        throw new Exception("2");
    } finally {
        System.out.print("C");
        throw new Exception("3");
    }
} catch (Exception e) {
    System.out.print(e.getMessage());
}

The question was "what the output will look like?"

I was pretty sure it would be AB2C3, BUT suprise suprise, it's not true.

The right answer is ABC3 (tested and really it's like that).

My question is, where did the Exception("2") go?

我以为因为finally子句始终会执行,因此在抛出Exception("3");的时候将catch中的异常覆盖了,今天突然又想起来到底catch中的异常是否还存在呢,搜了一下,csdn上飞天金刚给出了一个分析:

http://blog.csdn.net/sureyonder/article/details/5560538

自己写了一个其实跟上面的一样

代码语言:javascript
复制
 try
 {
     try{
     System.out.println("b");
     throw new IllegalArgumentException("2");
     }catch(IllegalArgumentException e)
     {
     System.out.println("c");
     throw new UnsupportedOperationException("3");
     }finally
     {
     System.out.println("d");
     throw new IndexOutOfBoundsException("4");
     }
 
 }catch(IndexOutOfBoundsException e)
 { 
     System.out.println(e.getMessage());
     e.printStackTrace();
 }

查看了一下程序的ExceptionTable

Exception table: from to target type 0 18 18 Class java/lang/IllegalArgumentException 0 38 37 any 0 56 56 Class java/lang/IndexOutOfBoundsException

三个exception都在table里面,只不过抛出的只是最后一个而已。其他两个都被java当做垃圾给扔了,而且第二个没有被catch的exception类型未知。exception table是什么原理呢?有待查询。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档