Rules of Exceptions in Method Overriding

May 31, 2011 | Exceptions
After knowing Rules of "Access Specifiers in Method Overriding", let us find the "Rules of Exceptions in Method Overriding".

The rule says "Subclass overridden method cannot throw more checked exceptions than that of super class method".

Let us explain the rule through a program for clear and easy understanding.

The following program does not compile as subclass display() method throws Exception, the super class of IOException (thrown by super class display method).

import java.io.*;
class Test
{
    public void display() throws IOException  {    }
}
public class Demo extends Test
{
    public void display() throws Exception  {   }  //  throwing super class exception
}

The above program does not compile as subclass display() method cannot throw more than IOException. That is, it cannot throw the superclasses of IOException. It can throw either the same (IOException) or its subclass FileNotFoundException.

Observe the compiler message.

Exceptions in Method Overriding

We know in exception hierarchy, that IOException super class is Exception and subclass is FileNotFoundException.

Following combinations of the above code works nice.

The following program works well as subclass display() method throws the same exception, IOException, thrown by super class display() method.

import java.io.*;
class Test
{
    public void display() throws IOException  {    }
}
public class Demo extends Test
{
    public void display() throws IOException  {   }   // throwing the same
}

The following program also works well as subclass display() method throws the subclass exception FileNotFoundException of IOException.

import java.io.*;
class Test
{
    public void display() throws IOException  {    }
}
public class Demo extends Test
{
    public void display() throws FileNotFoundException {   }   // throwing subclass exception
}

A novice should be aware of this rule while coding.

One stop destination for all Java Exception world.

Looks confusing, the following.

  1. Do you know, a try block can be written with finally block without catch block? 2. Do you know, the three styles of handling exceptions. 3. Do you know, the rules imposed by access specifiers in method overriding? 4. Do you know, how to avoid try-catch even with checked exceptions?