Monday 6 October 2014

Exceptions with method overriding in java

In java methods can throw the different checked/unchecked exceptions, this seems to be simple as long as we are talking about the single methods in java but when we deal with method overriding in java the concept of exception which can be thrown by overriding or overridden method are bit tricky. The overriding method cannot throw the new/broader exception than the overridden method is throwing but this case is only true for checked exception and not true for unchecked/runtime exception.

If overriding method is throwing a checked exception which is new/broader than your overridden method exception then your code will not compile.

The combination of base class overridden method and derived class overriding method with respect to exceptions can be categorized into the below five cases as:

1.    Base class method throwing no exception and derived class method is throwing exception.
       •    In case of checked exception code will not compile
       •    In case of runtimeException code will work fine.

2.    Base class method throwing less newer/broader exception than derived class method is throwing.   
       Suppose base class overridden method is throwing ArithmeticException and derived class overriding
       method is throwing general Exception so then code will not compile.
      •    In case of checked exception code will not compile
      •    In case of runtimeException code will work fine.

3.    Both base and derived class overridden method throw same exception
       •    Code will compile and run perfectly in both cases of checked and unchecked exception.

4.    Base class overridden method throwing newer/broader exception than derived class overriding method.
       Suppose base class overridden method is throwing general Exception and derived class overriding
       method is throwing ArithmeticException so then code will compile and work fine.
       •     Code will compile and run perfectly in both cases of checked and unchecked exception.

5.    Base class overridden method is throwing exception but Derived class overriding method is not 
       throwing  exception.
      •    Code will compile and run perfectly in both cases of checked and unchecked exception.