Reputation: 23
I am reading about inheritance and exceptions. When I try to compile the below code in console, I am getting compiler error. Still I couldn't figure out why. But if I change the method name in my class B, everything works fine. Please help.
Here is my code:
import java.io.IOException;
class A {
public void print() throws IOException {
System.out.println("In Class A.");
throw new IOException("Printed in A.");
}
}
class B extends A {
public void print() throws Exception {
System.out.println("In Class B.");
throw new Exception("Printed in B.");
}
}
public class TestPrint {
public static void main (String args[]) {
B b = new B();
try {
b.print();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Upvotes: 2
Views: 68
Reputation: 78
You can't throw higher exception in inheritance hierarchy in overridden method, That is IOException
is subclass of Exception Class.
You can throw any exception that is subclass of IOException
in overridden method
Upvotes: 1
Reputation: 15553
An overridden method can not throw Checked Exception which is higher in hierarchy than original method.
Exception
is super class of IOException
.
So your print()
method sub class (B
) can throw either IOException
or any of the sub classes of IOException
.
Change your class B
, as shown below:
class B extends A {
public void print() throws IOException {
System.out.println("In Class B.");
throw new IOException("Printed in B.");
}
}
Upvotes: 4