
当您尝试处理由特定方法抛出的(已检查的)异常时,您需要使用Exception类或发生异常的超类来捕获它。
同样,在重写超类的方法时,如果它抛出异常−
子类中的方法应该抛出相同的异常或其子类型。
子类中的方法不应该抛出其超类型。
立即学习“Java免费学习笔记(深入)”;
您可以在不抛出任何异常的情况下进行重写。
当您有三个名为Demo,SuperTest和Super的类(层次结构)继承时,如果Demo和SuperTest有一个名为sample()的方法。
实时演示
class Demo {
public void sample() throws ArrayIndexOutOfBoundsException {
System.out.println("sample() method of the Demo class");
}
}
class SuperTest extends Demo {
public void sample() throws IndexOutOfBoundsException {
System.out.println("sample() method of the SuperTest class");
}
}
public class Test extends SuperTest {
public static void main(String args[]) {
Demo obj = new SuperTest();
try {
obj.sample();
}catch (ArrayIndexOutOfBoundsException ex) {
System.out.println("Exception");
}
}
}sample() method of the SuperTest class
如果你捕获异常的类与抛出的异常不相同或者不是异常的超类,你将会得到一个编译时错误。
同样地,在重写方法时,抛出的异常应该与被重写方法抛出的异常相同或者是其超类,否则会发生编译时错误。
演示
import java.io.IOException;
import java.io.EOFException;
class Demo {
public void sample() throws IOException {
System.out.println("sample() method of the Demo class");
}
}
class SuperTest extends Demo {
public void sample() throws EOFException {
System.out.println("sample() method of the SuperTest class");
}
}
public class Test extends SuperTest {
public static void main(String args[]) {
Demo obj = new SuperTest();
try {
obj.sample();
}catch (EOFException ex){
System.out.println("Exception");
}
}
}Test.java:12: error: sample() in SuperTest cannot override sample() in Demo
public void sample() throws IOException {
^
overridden method does not throw IOException
1 error
D:\>javac Test.java
Test.java:20: error: unreported exception IOException; must be caught or declared to be thrown
obj.sample();
^
1 error以上就是在Java中覆盖时,父子层次结构对于抛出异常重要吗?的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号