What I knew so far is that a subclass, if overriding a superclass method, should throw the same exception or subclass of the exception.
For instance:
It is right
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) {
}
}
}
This is not true
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) {
}
}
}
But my question is: why is this code block considered the right compiler?
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) {
}
}
}
user1678517
source
share