Is parent child hierarchy important on throws while overriding in Java?

JavaObject Oriented ProgrammingProgramming

When you try to handle an exception (checked) thrown by a particular method, you need to catch it using the Exception class or super class of the Exception occurred.

In the same way while overriding the method of a super class, if it throws an exception −

  • The method in the sub-class should throw the same exception or its sub type.

  • The method in the sub-class should not throw its super type.

  • You can override it without throwing any exception.

When you have three classes named Demo, SuperTest and, Super in (hierarchical) inheritance, if Demo and SuperTest have a method named sample().

Example

 Live Demo

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");
      }
   }
}

Output

sample() method of the SuperTest class

If the class with which you catch an exception is not same or, exception or, super class of the raised exception, you will get a compile time error.

In the same way, while overriding a method the exception thrown should be same or, super class of the exception thrown by the overridden method otherwise a compile time error occurs.

Example

 Live Demo

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");
      }
   }
}

Output

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
raja
Published on 14-Oct-2019 14:14:03
Advertisements