Java Reference
In-Depth Information
You should be explicit in your
throws
clause, listing all the exceptions you
know that you throw, even when you could encompass several excep-
tions under some superclass they all share. This is good self-document-
ation. Deciding how explicit you should be requires some thought. If you
are designing a general interface or superclass you have to think about
how restrictive you want to be to the implementing classes. It may be
quite reasonable to define a general exception you use in the interface's
throws
clause, and to expect that the implementing classes will be more
specific where possible. This tactic is used by the
java.io
package, which
defines a general
IOException
type for its methods to throw. This lets im-
plementing classes throw exceptions specific to whatever kind of I/O is
being done. For example, the classes that do I/O across network chan-
nels can throw various network-related subclasses of
IOException
, and
those dealing with files throw file-related subclasses.
12.3.1.
tHRows
Clauses and Method Overriding
When you override an inherited method, or implement an inherited ab-
stract method, the
tHRows
clause of the overriding method must be com-
patible with the
throws
clause of the inherited method (whether abstract
or not).
The simple rule is that an overriding or implementing method is not al-
lowed to declare more checked exceptions in the
tHRows
clause than the
inherited method does. The reason for this rule is quite simple: Code
written to deal with the original method declaration won't be prepared
to catch any additional checked exceptions and so no such exceptions
are allowed to be thrown. Subtypes of the declared exceptions can be
thrown because they will be caught in a
catch
block for their supertype.
If the overriding or implementing method does not throw a checked ex-
ception then it need not redeclare that exception. For example, as you
saw in "
Strategies for Cloning
"
on page
101
,
a class that implements
Cloneable
need not declare that
clone
may throw a
CloneNotSupportedEx-
ception
. Whether to declare it or not is a matter of designif you declare
it in the overriding method then subclasses of your class will be allowed
to throw the exception in that method, otherwise they will not.