Can we change an exception of a method with throws clause from unchecked to checked while overriding it in java?


A checked exception is an exception that occurs at the compile time, these are also called as compile time exceptions. These exceptions cannot simply be ignored at the time of compilation; the programmer should take care of (handle) these exceptions.

An unchecked exception is an exception that occurs at the time of execution. These are also called as Runtime Exceptions. These include programming bugs, such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation.

Unchecked to checked

When a method in superclass throws an unchecked exception the method the subclass method overriding cannot throw a checked exception.

Example

In the following example we have an abstract method in the class named Super which throws an unchecked exception (ArithmeticException).

In the subclass we are overriding this method and throwing a checked exception (IOException).

 Live Demo

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
import java.io.InvalidClassException;
abstract class Super {
   public abstract String readFile(String path) throws ArithmeticException;
}
public class ExceptionsExample extends Super {
   @Override
   public String readFile(String path) throws FileNotFoundException {
      // TODO Auto-generated method stub
      return null;
   }
}

Output

ExceptionsExample.java:12: error: readFile(String) in ExceptionsExample cannot
override readFile(String) in Super
   public String readFile(String path) throws FileNotFoundException {
              ^
   overridden method does not throw FileNotFoundException
1 error

But, when a method in superclass throws a checked exception the method the subclass method overriding can throw an unchecked exception.

Example

In the following example we are Just swapping the exceptions of the methods in superclass and subclass.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
import java.io.InvalidClassException;
abstract class Super{
   public abstract String readFile(String path) throws FileNotFoundException ;
}
public class ExceptionsExample extends Super {
   @Override
   public String readFile(String path) throws ArithmeticException {
      // TODO Auto-generated method stub
      return null;
   }
}

If you compile the above program, it gets compiled without compile time errors

Output

Error: Main method not found in class ExceptionsExample, please define the main method as:
   public static void main(String[] args)
   or a JavaFX application class must extend javafx.application.Application

Updated on: 29-Jun-2020

364 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements