Java Reference
In-Depth Information
CHAPTER 9
Exceptions and Logging
Exceptions are a way of describing exceptional circumstances within a program. They
are an indicator that something unexpected (exceptional) has occurred. For that reason,
exceptions are efficient at interrupting the current flow of the program and signaling that
there is something that requires attention. As such, programs that utilize exceptions judi-
ciously benefit from a better control flow and become more robust. Even so, using ex-
ceptions indiscriminately can cause performance degradation.
Within Java, exceptions can be
thrown
or
caught
. Throwing an exception involves
telling the code that you have encountered an exception, using the
throw
keyword to
signal the JVM to find any code capable of handling this exceptional circumstance with-
in the current stack. Catching an exception involves telling the compiler which excep-
tions you can handle, and on which part of the code you want to monitor for these ex-
ceptions to occur. This is denoted within the
try
/
catch
Java block (described in Re-
cipe 9-1)
inherited from
Throwable
can be defined in the catch clause of a
try
/
catch
state-
ment. The
Error
classes are primarily used by the JVM to denote serious and/or fatal
errors. According to the Java documentation, applications are not expected to catch
Er-
ror
exceptions since they are considered fatal (think of a computer being on fire). The
bulk of exceptions within a Java program will be inherited from the
Exception
class.