多个例外

时间:2015-07-04 14:48:22

标签: java exception

当我执行此代码时,我得到caughtjava.lang.CloneNotSupportedException作为输出!为什么NullPointerException没有被抓住?

package arrays;

public class NestedTry {
    public static void main(String s[])
    {
        try{
            try{
                throw new NullPointerException();
            }
            finally{
                throw new CloneNotSupportedException();
            }
        }
        catch(Exception e)
        {
            System.out.println("caught"+e.toString());
            //which excpetion will be printed here?? :P
        }
    }
}

1 个答案:

答案 0 :(得分:1)

肯定会执行finally块。

try{
        throw new NullPointerException();
    }
    finally{
        throw new CloneNotSupportedException();
        }

在上面的代码中,第一个NullPointerException()被抛出,但对于tryfinally块再次抛出CloneNotSupportedException();

所以最终

catch(Exception e)
 {
    System.out.println("caught"+e.toString());
    //which excpetion will be printed here?? :P
 }

上述catch代替NullPointerException抓取finally阻止CloneNotSupportedException并打印caughtjava.lang.CloneNotSupportedException