What I have known till now is that a subclass if overriding a superclass method should throw the same exception or a subclass of the exception.
For example:
This is correct
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 Incorrect
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 this code block is considered correct by 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) {
}
}
}