Overriding Method with Exception

前端 未结 1 1163
滥情空心
滥情空心 2020-12-20 15:10

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 overrid

相关标签:
1条回答
  • 2020-12-20 16:03

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

    0 讨论(0)
提交回复
热议问题