Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

java - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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?)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...