Can the overriding method throw the super-type of the exception thrown by the overridden method in Java?

JavaObject Oriented ProgrammingProgramming

If the super-class method throws certain exception, the method in the sub-class should not throw its super type.

Example

In the following example the readFile() method of the super-class throws FileNotFoundException exception and, the readFile() method of the sub-class throws an IOException, which is the super type of the FileNotFoundException.

 Live Demo

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
abstract class Super {
   public String readFile(String path)throws FileNotFoundException {
      throw new FileNotFoundException();
   }
}
public class ExceptionsExample extends Super {
   @Override
   public String readFile(String path)throws IOException {
      //method body ......
   }
}

Compile time error

On compiling, the above program gives you the following output −

ExceptionsExample.java:13: error: readFile(String) in ExceptionsExample cannot override readFile(String) in Sup
   public String readFile(String path)throws IOException {
                 ^
overridden method does not throw IOException
1 error
raja
Published on 15-Oct-2019 07:09:31
Advertisements