下面的语句来自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)
最佳答案
您没有在派生类的构造函数中捕获任何内容。您可以在 main 方法中捕获异常。因此,您并不与您发布的引文相矛盾。
关于java - "A derived-class constructor cannot catch exceptions thrown by its base-class constructor."但能够捕获它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25698681/