Java, Software Development

Java – Override method to not throw Exception

Sometimes we want to override a Java method and do not throw or rethrow (propagate) Exceptions from it. By design, Java allows child classes to override a method from a parent class to ignore Exceptions – both checked and unchecked. But what if we want to reuse the original parent method within that overridden method? Consider the following codes  –  we have child and parent classes.

Java Parent-Child Classes With Method That Throw Exceptions

The Child class extends from the Parent class as follows. Usually, when overriding a method, most of us would copy the same method signature from the parent class.

11-11-2016-5-00-37-pm

As a result, we need to wrap the method call within a try-catch. Now that call could be anywhere in the codebase. What if we don’t want to wrap the calling codes within try-catch?

11-11-2016-5-01-34-pm

We can override the method in the Child class and call the parent method with a try-catch. Then, we can either rethrow the Exception or swallow it in the catch clause.

Let The Child class Decide about the Parent’s Exception

For instance, the overridden method printName throws an Exception as its parent version of printName. This will require any codes calling our overridden Java method to handle the Exception.

However, we could change the overridden method’s signature and swallow the Exception from the parent method.

Then, the child method will not force our calling codes to declare or handle the exception.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like