Java Reference
In-Depth Information
12.3. The
tHRows
Clause
The definition of the
replaceValue
method declares which checked excep-
tions it throws. The language requires such a declaration because pro-
grammers invoking a method need to know the exceptions it can throw
just as much as they need to know its normal behavior. The checked ex-
ceptions that a method throws are as important as the type of value it
returns. Both must be declared.
The checked exceptions a method can throw are declared with a
tHRows
clause, which declares a comma-separated list of exception types. Only
those exceptions that are not caught within the method must be listed.
You can throw checked exceptions that are extensions of any type of
exception in the
throws
clause because you can use a class polymorph-
ically anywhere its superclass is expected. A method can throw many
classes of checked exceptionsall of them extensions of a particular excep-
tion classand declare only the superclass in the
throws
clause. By doing
so, however, you hide potentially useful information from programmers
invoking the method: They won't know which of the possible extended
exception types could be thrown. For documentation purposes, the
tHRows
clause should be as complete and specific as possible.
The contract defined by the
throws
clause is strictly enforcedyou can
throw only a type of checked exception that has been declared in the
tHRows
clause. Throwing any other type of checked exception is invalid,
whether you use
throw
directly or use it indirectly by invoking another
method. If a method has no
throws
clause, that does not mean that
any
exceptions can be thrown: It means that
no
checked exceptions can be
thrown.
All the standard runtime exceptions (such as
ClassCastException
and
ArithmeticException
) are extensions of the
RuntimeException
class. The
more serious errors are signaled by exceptions that are extensions of
Er-
ror
, and these exceptions can occur at any time in any code.
RuntimeEx-
ception
and
Error
are the only exceptions you do not need to list in your
throws
clauses. They are ubiquitous, and every method can potentially