I was practicing exception handling mechanisms with method overriding in java...My code is as follows:
class base {
void show() {
System.out.println("in base class method");
}
}
class derived extends base {
void show() throws IOException {
System.out.println("in derived class method");
throw new IOException();
}
}
class my {
public static void main(String[] args) {
try {
base b = new derived();
b.show();
}
catch (IOException e) {
System.out.println("exception occurred at :" + e);
}
}
}
Showing an error :
So, I corrected following:
void show() throws IOException{
and it is working correctly...
One more experiment I did :
void show() throws Exception{
but it was also showing an error:
As I understand, this is because of an overridden method's throws
clause should mention the exact checked exception in throws
clause of super class method.
As in second case, if I write IOException
's superclass Exception
in throws clause, it also shows an error. why? Even if Exception
is parent class of all exceptions.
I just experimented...what this error tells I don't know...
Can any one please explain what it says and what are the constraints for mentioning checked exception in throws
clause of an overridden method?