Method Overriding with Exceptions in Java

March 17, 2015

Understanding method overriding with Exceptions has made some confusions in my mind. So I tried to list all the possible cases in terms of declarations of exceptions in super class method. The list of 3 main cases are as follows.

Case 1: Super class method declares NO exceptions

Here there are only 2 possible sub cases.
  1. Sub class method does not declare any Exceptions. This is the most obvious one since there are no Exceptions involved. So I'll omit the code sample.
  2. Sub class method declares one or more Unchecked exceptions.

Case 2: Super class method declares one or more Checked exceptions

In this case there are 3 possible sub cases.
  1. Sub class method can refrain from declaring any Exception
  2. Sub class method can declare at least one of the corresponding Exceptions declared in the super class method or one of its sub classes. Notice that FileNotFoundException is a sub class of IOException.
  3. Sub class method can declare all of the corresponding Exceptions declared in the super class or their sub classes.

Case 3: Super class method declares one or more Unchecked exceptions

Unchecked exceptions don't give us any trouble (in terms of method overriding)  like Checked Exceptions. We don't have to consider the Unchecked Exceptions declared in the super class method hence it is legal to refrain from declaring any Exception or it is completely legal to declare any Unchecked Exception without considering the inheritance hierarchy in the sub class method.  But it's very important to remember that It it possible to throw Unchecked Exceptions even if we declare them or not.

Have look at the following example. Notice that ArithmeticException and NullPointerException are not in the same inheritance hierarchy.

We can define a 4th case where the list of exceptions declared in the super class method consists of both Checked & Unchecked exceptions, but since Checked & Unchecked exceptions are independent from each other we can treat the declaration part independently as well. ie we can apply case 2 and case 3 separately.

No comments:

Post a Comment