Java Reference
In-Depth Information
1.14. Exceptions
What do you do when an error occurs in a program? In many languages,
error conditions are signaled by unusual return values like 1 . Program-
mers often don't check for exceptional values because they may assume
that errors "can't happen." On the other hand, adding error detection and
recovery to what should be a straightforward flow of logic can complicate
that logic to the point where the normal flow is completely obscured. An
ostensibly simple task such as reading a file into memory might require
about seven lines of code. Error checking and reporting expands this to
40 or more lines. Making normal operation the needle in your code hay-
stack is undesirable.
Checked exceptions manage error handling. Checked exceptions force
you to consider what to do with errors where they may occur in the code.
If a checked exception is not handled, this is noticed at compile time, not
at run time when problems have been compounded because of the un-
checked error.
A method that detects an unusual error condition throws an exception.
Exceptions can be caught by code farther back on the calling stackthis
invoking code can handle the exception as needed and then continue ex-
ecuting. Uncaught exceptions result in the termination of the thread of
execution, but before it terminates the thread's UncaughtExceptionHandler
is given the opportunity to respond to the exception as best it canperhaps
doing nothing more than reporting that the exception occurred. THReads
and UncaughtExceptionHandlers are discussed in detail in Chapter 14 .
An exception is an object, with type, methods, and data. Representing
exceptions as objects is useful, because an exception object can include
data, methods, or both to report on or recover from specific kinds of
exceptions. Exception objects are generally derived from the Exception
class, which provides a string field to describe the error. All exceptions
must be subclasses of the class Throwable , which is the superclass of Ex-
ception .
The paradigm for using exceptions is the trycatchfinally sequence: you
try something; if that something throws an exception, you catch the ex-
 
Search WWH ::




Custom Search