Java Reference
In-Depth Information
Figure 9-1
.
Part of the exception class hierarchy in Java
Within the JVM there are two types of exceptions: checked and unchecked.
Checked exceptions are enforced by methods. In the method signature, you can specify
the kind of exceptions a method can throw. This requires any caller of the method to
create a
try
/
catch
block, which handles the exceptions that were declared within the
method signature. Unchecked exceptions do not require such a stringent convention,
and are free to be thrown anywhere without enforcing the implementation of a
try
/
catch
block. Even so, unchecked exceptions (as described in Recipe 9-6) are
usually discouraged because they can lead to threads unraveling (if nothing catches the
exception) and poor visibility of problems. Exception classes that inherit from
RuntimeException
are considered to be unchecked exceptions, whereas exception
classes that inherit directly from
Exception
are considered to be checked excep-
tions.
Be aware that the act of throwing exceptions is expensive (compared with other
language construct alternatives), and as such throwing exceptions makes a poor substi-
tute for control flow. For example, you shouldn't throw an exception to indicate an ex-
pected result of a method call (say a method like
isUsernameValid (String
username
). It is a better practice to call the method and return a
boolean
with the
result than try to throw an
InvalidUsernameException
to indicate failure.
While exceptions play an essential role in solid software development, logging of
exceptions can be just as important. Logging within an application helps the developer