While overriding can the subclass choose not to throw an exception in java?

JavaObject Oriented ProgrammingProgramming

If the super-class method throws certain exception, you can override it without throwing any exception.

Example

In the following example the sampleMethod() method of the super-class throws FileNotFoundException exception and, the sampleMethod() method does not throw any exception at all. Still this program gets compiled and executed without any errors.

 Live Demo

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
abstract class Super {
   public void sampleMethod()throws FileNotFoundException {
      System.out.println("Method of superclass");
   }
}
public class ExceptionsExample extends Super {
   public void sampleMethod() {
      System.out.println("Method of Subclass");
   }
   public static void main(String args[]) {
      ExceptionsExample obj = new ExceptionsExample();
      obj.sampleMethod();
   }
}

Output

Method of Subclass
raja
Published on 15-Oct-2019 07:12:20
Advertisements