Home >Java >javaTutorial >Is parent-child hierarchy important for throwing exceptions when overriding in Java?
When you try to handle a (checked) exception thrown by a specific method, you need to catch it using the Exception class or the superclass where the exception occurred .
Similarly, when overriding a method of a super class, if it throws an exception −
The method in the subclass should throw the same exception or its subtype .
Methods in subclasses should not throw out of their supertype.
You can override without throwing any exception.
When you have three classes (hierarchies) named Demo, SuperTest and Super that inherit, if Demo and SuperTest have a class named sample() method.
Real-time demonstration
class Demo { public void sample() throws ArrayIndexOutOfBoundsException { System.out.println("sample() method of the Demo class"); } } class SuperTest extends Demo { public void sample() throws IndexOutOfBoundsException { System.out.println("sample() method of the SuperTest class"); } } public class Test extends SuperTest { public static void main(String args[]) { Demo obj = new SuperTest(); try { obj.sample(); }catch (ArrayIndexOutOfBoundsException ex) { System.out.println("Exception"); } } }
sample() method of the SuperTest class
If the class you catch the exception is not the same as the exception thrown or is not the superclass of the exception, You will get a compile time error.
Similarly, when overriding a method, the exception thrown should be the same as the exception thrown by the overridden method or its superclass, otherwise a compile-time error will occur.
Demonstration
import java.io.IOException; import java.io.EOFException; class Demo { public void sample() throws IOException { System.out.println("sample() method of the Demo class"); } } class SuperTest extends Demo { public void sample() throws EOFException { System.out.println("sample() method of the SuperTest class"); } } public class Test extends SuperTest { public static void main(String args[]) { Demo obj = new SuperTest(); try { obj.sample(); }catch (EOFException ex){ System.out.println("Exception"); } } }
Test.java:12: error: sample() in SuperTest cannot override sample() in Demo public void sample() throws IOException { ^ overridden method does not throw IOException 1 error D:\>javac Test.java Test.java:20: error: unreported exception IOException; must be caught or declared to be thrown obj.sample(); ^ 1 error
The above is the detailed content of Is parent-child hierarchy important for throwing exceptions when overriding in Java?. For more information, please follow other related articles on the PHP Chinese website!