gpt4 book ai didi

java - "A derived-class constructor cannot catch exceptions thrown by its base-class constructor."但能够捕获它

转载 作者:行者123 更新时间:2023-12-01 22:43:41 26 4
gpt4 key购买 nike

下面的语句来自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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com