class A {
public void process() { System.out.print("A,"); }
}
public class B extends A
{
public void process() throws IOException { //LINE 23
super.process();
System.out.print("B,");
throw new IOException();
}
public static void main(String[] args) {
try { new B().process(); }
catch (IOException e) { System.out.println("Exception"); }
}
}
This question is from SCJP 6 , book says that compilation will fail due to an error at Line 23. But what i learned is , you can't throw broader exception when you overide method from parent class. In this Example my parent class method throws no exception , and my ovridden method throws IOException which is subclass of Exception. Then why its not working?
Moreover , i am considering that if my parent class method throws no exception , its by default considered as (( public void process() throws Exception. ))
. Is that True??
Your understanding is not correct
public void process(){}
and
public void process() throws Exception{}
are not equivalent. what you can say is equivalent is:
public void process() throws RuntimeException{}
by definition you can not throw a broader exception from a overridden method in subclass. but you can always throw an unchecked exception from any method.
For better understanding please read