![](/img/trans.png)
[英]Why List<String> can't simultaneously be argument of a Base-class generic method and Derived-class non-generic method?
[英]“A derived-class constructor cannot catch exceptions thrown by its base-class constructor.” But able to catch it
下面的语句来自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方法中捕获异常。 因此,您不会与您发布的报价相矛盾。
这是您的派生类构造函数必须具有的外观,以便捕获基类构造函数的异常:
Derived() {
try {
super();
} catch (CloneNotSupportedException e) {
System.out.println("We have indeed caught an exception from the "+
"base-class constructor! The book was wrong!");
}
}
试试看,看看结果如何。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.