While implementing an abstract factory pattern for my software engineering class I noticed something that seemed weird to me: I defined an interface with several methods, each method was declared to throw several exceptions using the standard throws
keyword.
When I created the implementation class for that method, I noticed that I do not have to throw all of the exceptions the interface specified. Actually, I only needed to throw one exception for the method I was overriding for the specific implementation and Java let me. I tried researching more on the relationship between exceptions and interfaces finding nothing.
Turning into the real Java bible, the Java Language Specification (I recommend the free download), I encountered the following sentence in the spec (page 299):
The throws clause of an overriding method may not specify that this method will
result in throwing any checked exception which the overridden method has not permitted, by its throws clause, to throw. When interfaces are involved, more than one method declaration may be overridden by a single overriding declaration. In this case, the overriding declaration must have a throws clause that is compatible with all the overridden declarations.
So an implementing or overriding method (from an interface or a super class) may only throw exceptions that are among the ones the interface or super class specified in the original method declaration. By converse, this means that if an overriding method does not need to throw exceptions that are thrown by the interface or super class’ method, it does not have to. In other words:
An overriding method can throw any of the exceptions the original method throws, or none of them.