到目前为止我所知道的是,如果覆盖超类方法的子类应该抛出相同的异常或异常的子类。
例如:
这是对的
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) {
}
}
}