package com.rnd.core.java;
import java.io.IOException;
public class TestExceptionInheritance {
public void checkExcpetions () throws ArrayIndexOutOfBoundsException{
System.out.println("Inside TestExceptionInheritance ParentClass");
throw new ArrayIndexOutOfBoundsException();
}
}
package com.rnd.core.java;
import javax.sound.midi.MidiUnavailableException;
public class TestExceptionInheritance2 extends TestExceptionInheritance {
public void checkException () throws MidiUnavailableException {
System.out.println("Hello");
throw new MidiUnavailableException();
}
@Override
public void checkExcpetions() throws StringIndexOutOfBoundsException {
// TODO Auto-generated method stub
//super.checkExcpetions();
System.out.println("HI");
}
public static void main(String[] args) throws Exception {
TestExceptionInheritance obj = new TestExceptionInheritance2();
obj.checkExcpetions();
}
}
I have overriden the checkException Method of the parent class in my subclass but I throw a different exception here.
I want to understand why the compiler allows me to throw an altogether different exception; though I know that the method version would be decided based on the reference type.
-------------------Edit 1---------------------------
I have added an @override notation over the overridden method. Overridden method allows me to throw StringIndexOutOfBoundException and RunTimeException along with ArrayIndexOutOfBoundException but not any other exception like for example Exception.
According to the Exception class hierarchy, both StringIndexOutOfBoundException and ArrayIndexOutOfBoundException are subclasses of IndexOutOfBoundException.
How and why does the compiler allows me to throw StringIndexOutOfBoundException because ArrayIndexOutOfBoundException will be never be caught in StringIndexOutOfBoundException.
Thanks for your help.