Java Reference
In-Depth Information
Chapter 12. Exceptions and Assertions
A slipping gear could let your M203 grenade launcher fire when you
least expect it. That would make you quite unpopular in what's left
of your unit.
The U.S. Army's PS magazine, August 1993
During execution, applications can run into many kinds of errors of vary-
ing degrees of severity. When methods are invoked on an object, the
object can discover internal state problems (inconsistent values of vari-
ables), detect errors with objects or data it manipulates (such as a file or
network address), determine that it is violating its basic contract (such
as reading data from an already closed stream), and so on.
Many programmers do not test for all possible error conditions, and
for good reason: Code becomes unintelligible if each method invocation
checks for all possible errors before the next statement is executed. This
trade-off creates a tension between correctness (checking for all errors)
and clarity (not cluttering the basic flow of code with many error checks).
Exceptions provide a clean way to check for errors without cluttering
code. Exceptions also provide a mechanism to signal errors directly
rather than indirectly with flags or side effects such as fields that must
be checked. Exceptions make the error conditions that a method can sig-
nal an explicit part of the method's contract. The list of exceptions can
be seen by the programmer, checked by the compiler, and preserved (if
needed) by extended classes that override the method.
An exception is thrown when an unexpected error condition is en-
countered. The exception is then caught by an encompassing clause fur-
ther up the method invocation stack. Uncaught exceptions result in the
termination of the thread of execution, but before it terminates, the
thread's UncaughtExceptionHandler is given the opportunity to handle the
exception as best it can, usually printing useful information (such as a
call stack) about where the exception was thrownsee " Threads and Ex-
ceptions " on page 379 .
 
Search WWH ::




Custom Search