Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding Method with Exception

So here is the quote from the book:

The overriding method must NOT throw checked exceptions that are new or broader than those declared by the overridden method. For example, a method that declares a FileNotFoundException cannot be overridden by a method that declares a SQLException, Exception, or any other non-runtime exception unless it's a subclass of FileNotFoundException.

Now here is my question, if the method in the superclass throws an exception, then can the overriding method NOT throw an exception at all?

Because I just tried this in Java, where the overriding method did not throw any exceptions, and there was no error.

Please explain.

like image 226
Evolutionary High Avatar asked Oct 03 '13 19:10

Evolutionary High


1 Answers

You can declare an overriding method as throwing less types of exceptions than the superclass, you just can't introduce new ones. The subclass method has to be compatible with the behavior of the superclass method. More exactly, you have to be able to substitute objects of the subclass for objects of the superclass without breaking anything (where adding a new checked exception to the throws clause would mean things calling it would have to change their code to handle it).

(The idea behind this is the Liskov Substitution Principle: a program should be able to deal with objects at a high level without getting bogged down in details about everything's exact type. If subclasses can introduce changes that mean the program has to pick them out and handle them differently then it defeats the purpose of abstraction.)

So an overriding method can be declared as throwing no checked exceptions at all (by omitting the throws clause entirely), because that doesn't require changes to any callers.

There are examples in the JDK, such as in java.io, where the subclass can't possibly throw an exception declared by the super class (see the ByteArrayOutputStream close method). Here the close method could have had its throws clause removed, since it never throws IOException. (Maybe it was left on the chance someone would want to subclass it with a version that did throw IOException?)

like image 63
Nathan Hughes Avatar answered Oct 05 '22 23:10

Nathan Hughes