Exception Handling in Method Overriding

Let’s learn about Exception handling in Method overriding. There are few things to remember when overriding a method with exception handling. There are certain restrictions while overriding a method in case of exception handling in Java. Broadly there are two rules –

 

If the superclass method does not declare an exception

If the superclass method does not declare any exception, then subclass overridden method cannot declare checked exception but it can declare unchecked exceptions. or we can say “Subclass overridden method cannot throw more checked exceptions than that of superclass method“.

The output of the above code will show you compile time error.

It can be noted here that parent class’ display() method doesn’t have any throws clause whereas overridden method in the subclass declares IOException in its throws clause which is a checked exception. That’s why the compile time error.

If we change the throws clause in subclass method to any unchecked exception then it won’t result in compiler error.

 

Selenium Tutorial:

If you liked this video, then please subscribe to our YouTube Channel for more video tutorials.

 

If the superclass method declares an exception

If superclass method has declared an exception using throws clause then subclass overridden method can do one of the three things.

 

A. If super class method has declared an exception then the subclass can declare the same exception as declared in the superclass method.

 

B. A subclass can declare the subtype exception of the exception declared in the superclass method.

 

Here in super class displayMsg() method throws IOException whereas in subclass overridden displayMsg() method throws FileNotFoundException. Since FileNotFoundException is the subtype (Child class) of IOException so no problem here but subclass method can not declare any exception that is up in the hierarchy than the exception declared in the super class method.

 

C. Subclass overridden method declares no exception. Subclass overridden method can choose to not throw any exception at all even if super class method throws an exception.

That’s all about the exception handling in method overriding. If you have any doubt, Please feel free and write us.

0 Comment

Leave a Reply