|
When you extend a class, the subclass inherits the methods of the superclass. You can replace (override) these inherited methods by declaring them again in the subclass. The method in the subclass is called the overriding method and the method in the superclass is called the overridden method. Java has a specific rule for declaration of these overriding methods. You cannot declare an overriding method to throw checked exceptions, which are not declared in the method in the superclass. The overriding method can do any of the following things when an overridden method is throwing a checked exception:
The overriding method may decide not to throw any exception.
The overriding method may throw exception that is a subclass of the exception thrown by the overridden method.
The overriding method cannot throw exception that is a superclass of the exception thrown by the overridden method. .
These rules are simple to understand with an example. Figure 5.5 illustrates these rules. It shows a Base class with aMethod() which declares to throw an IOException. The Derived1, Derived2, IllegalOne, and IllegalTwo classes are all subclasses of the Base class. Each of these classes overrides aMethod() of Base class.
![]() |
Figure 5.5 Legal and Illegal overriding of a method declaring an IOException
The class Derived1 overrides aMethod() but does not declare any exceptions. This is a legal declaration. You cannot declare exceptions other than the IOException (or its subclasses) in the overriding aMethod(). Therefore, not declaring any is perfectly ok. The Derived2 class overrides aMethod() and declares exceptions that are subclasses of IOException. Therefore, Derived2 also legally overrides aMethod(). However, the overriding methods in the classes IllegalOne and IllegalTwo declare exceptions which are not part of IOException’s class hierarchy (i.e. IOException and its subclasses). The aMethod() in IllegalOne declares to throw Exception which is a superclass of IOException. Therefore, this is not acceptable. The aMethod() in IllegalTwo declares to throw SomeOtherException which is not part of IOException hierarchy. Java does not allow this either. Therefore, the bottom line is that whenever you see a method declaring to throw a checked exception and if you want to override that method in any of the subclasses, it should never throw any exception other than that exception itself or its subclasses.
|
|
The rules for exceptions while overriding methods are applicable to only checked exceptions. Java compiler mandates that the checked exceptions are either declared (with throws clause) or handled in the methods where it may be thrown. You need not declare or handle any unchecked exceptions. Therefore, the overridden method in above example may declare to throw any runtime exception. For example, you can override aMethod as void aMethod() throws NullPointerException {} |