Java 异常丢失及finally子句

几天前在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:

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

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

 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是什么原理呢?有待查询。

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券