gpt4 book ai didi

java - 程序未编译

转载 作者:行者123 更新时间:2023-11-30 06:21:40 25 4
gpt4 key购买 nike

我正在阅读有关继承和异常的内容。当我尝试在控制台中编译以下代码时,出现编译器错误。我仍然不明白为什么。但是,如果我更改 B 类中的方法名称,一切正常。请帮忙。

这是我的代码:

import java.io.IOException;

class A {

public void print() throws IOException {
System.out.println("In Class A.");
throw new IOException("Printed in A.");
}

}

class B extends A {

public void print() throws Exception {
System.out.println("In Class B.");
throw new Exception("Printed in B.");
}

}

public class TestPrint {

public static void main (String args[]) {
B b = new B();
try {
b.print();
} catch (Exception e) {
e.printStackTrace();
}
}

}

最佳答案

被覆盖的方法不能抛出比原始方法层次更高的检查异常。

ExceptionIOException 的父类(super class)。

因此您的 print() 方法子类 (B) 可以抛出 IOExceptionIOException 的任何子类

改变你的类B,如下所示:

class B extends A {

public void print() throws IOException {
System.out.println("In Class B.");
throw new IOException("Printed in B.");
}

}

关于java - 程序未编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20158410/

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