到目前为止,我所知道的是,如果子类重写了父类(super class)方法,则应抛出相同的异常或该异常的子类。
例如:
这是正确的
class SuperClass {
public int doIt(String str, Integer... data)throws ArrayIndexOutOfBoundsException{
String signature = "(String, Integer[])";
System.out.println(str + " " + signature);
return 1;
}
}
public final class SubClass extends SuperClass {
public int doIt(String str, Integer... data) throws ArrayIndexOutOfBoundsException {
String signature = "(String, Integer[])";
System.out.println("Overridden: " + str + " " + signature);
return 0;
}
public static void main(String... args) {
SuperClass sb = new SubClass();
try {
sb.doIt("hello", 3);
} catch (Exception e) {
}
}
}
这是不正确的
class SuperClass {
public int doIt(String str, Integer... data)throws ArrayIndexOutOfBoundsException{
String signature = "(String, Integer[])";
System.out.println(str + " " + signature);
return 1;
}
}
public final class SubClass extends SuperClass {
public int doIt(String str, Integer... data) throws Exception {
String signature = "(String, Integer[])";
System.out.println("Overridden: " + str + " " + signature);
return 0;
}
public static void main(String... args) {
SuperClass sb = new SubClass();
try {
sb.doIt("hello", 3);
} catch (Exception e) {
}
}
}
但是我的问题是,为什么编译器认为此代码块正确?
class SuperClass {
public int doIt(String str, Integer... data)throws ArrayIndexOutOfBoundsException{
String signature = "(String, Integer[])";
System.out.println(str + " " + signature);
return 1;
}
}
public final class SubClass extends SuperClass {
public int doIt(String str, Integer... data) throws RuntimeException {
String signature = "(String, Integer[])";
System.out.println("Overridden: " + str + " " + signature);
return 0;
}
public static void main(String... args) {
SuperClass sb = new SubClass();
try {
sb.doIt("hello", 3);
} catch (Exception e) {
}
}
}
最佳答案
这是因为在Java中,每个方法都可以随时抛出RuntimeException
(或Error
)。它甚至不需要在方法签名的throws
部分中声明。因此,有可能抛出一个异常,该异常是您覆盖的方法中声明的异常的父类(super class)型,只要它仍然是RuntimeException
的子类型。
有关此行为的规范,请参见Chapter 11 (Exceptions) of the Java Language Specification,尤其是11.1.1. The Kinds of Exceptions,它定义了checked(需要在throws
子句中指定)和unchecked(不需要在throws
子句中指定)异常。