"派生类构造函数无法捕获其基类构造函数抛出的异常。"但能够抓住它

时间:2014-09-06 09:11:38

标签: java exception

以下语句来自java中的思考,“派生类构造函数无法捕获其基类构造函数抛出的异常。”但我能抓住它。谁能解释我哪里出错?

class Base {
    Base() throws CloneNotSupportedException {
        throw new CloneNotSupportedException();
    }
}

class Derived extends Base {

    Derived() throws CloneNotSupportedException, RuntimeException {}

    public static void main(String[] args) {
        try {
            Derived d = new Derived();
        }
        catch(CloneNotSupportedException e) {
            e.printStackTrace();
        }
        catch(RuntimeException re){}
    }
}

输出:

    java.lang.CloneNotSupportedException
    at Base.<init>(Coffee.java:4)
    at Derived.<init>(Coffee.java:9)
    at Derived.main(Coffee.java:14)

2 个答案:

答案 0 :(得分:2)

您没有在派生类的构造函数中捕获任何内容。您可以在main方法中捕获异常。因此,您并不反对您发布的报价。

答案 1 :(得分:1)

以下是派生类构造函数为了从基类构造函数中捕获异常而必须查看的方式:

Derived() {
   try { 
     super(); 
   } catch (CloneNotSupportedException e) {
     System.out.println("We have indeed caught an exception from the "+
          "base-class constructor! The book was wrong!");
   }
}

尝试一下,看看会发生什么。