在 Java 中重写方法时,父类子类继承关系对抛出异常重要吗?
当您尝试处理特定方法抛出的异常(已检查)时,您需要使用**Exception**类或发生异常的Exception的超类来捕获它。
同样,在重写父类的方法时,如果它抛出异常 -
子类中的方法应该抛出相同的异常或其子类型。
子类中的方法不应该抛出其超类型。
您可以在不抛出任何异常的情况下重写它。
当您在(分层)继承中拥有三个名为 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
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP