You can declare an overriding method as throwing fewer types of exceptions than the superclass, you simply cannot introduce new ones. The subclass method must be compatible with the behavior of the superclass method. More precisely, you should be able to substitute subclass objects for superclass objects without breaking anything (adding a new checked exception to the throws clause means that the things calling it will need to change their code to process it).
(The idea of ββthis is to replace Liskovβs principle : the program should be able to deal with objects at a high level without worrying about details about everything accurate. If subclasses can introduce changes that mean that the program must select and process them differently, then it the goal of abstraction wins.)
Thus, an overriding method can be declared as throwing excepted exceptions altogether (by omitting the throws clause completely), since this does not require changes for any callers.
There are examples in the JDK, for example, in java.io, where a subclass cannot throw an exception declared by the superclass (see ByteArrayOutputStream to close the method). Here, the close method could remove the throws clause, since it never throws an IOException. (Maybe this was in case someone wanted to subclass it with a version that actually throws an IOException?)
source share