Java Reference
In-Depth Information
11.1 Exception Handling
As we've discussed briefly in other parts of the text, problems that arise in a
Java program may generate exceptions or errors. An exception is an object that
defines an unusual or erroneous situation. An exception is thrown
by a program or the run-time environment and can be caught and
handled appropriately if desired. An error is similar to an exception
except that an error generally represents an unrecoverable situation
and should not be caught. Java has a predefined set of exceptions
and errors that may occur during the execution of a program.
Problem situations represented by exceptions and errors can have various kinds
of root causes. Here are some situations that cause exceptions to be thrown:
KEY CONCEPT
Errors and exceptions are objects
that represent unusual or invalid
processing.
Attempting to divide by zero.
An array index that is out of bounds.
A specified file that could not be found.
A requested I/O operation that could not be completed normally.
An attempt was made to follow a null reference.
An attempt was made to execute an operation that violates some kind of
security measure.
These are just a few examples. There are dozens of others that address very spe-
cific situations.
As many of these examples show, an exception can represent a truly errone-
ous situation. But as the name implies, they may simply represent an exceptional
situation. That is, an exception may represent a situation that won't occur under
usual conditions. Exception handling is set up to be an efficient way to deal with
such situations, especially given that they don't happen too often.
We have several options when it comes to dealing with exceptions. A program
can be designed to process an exception in one of three ways. It can:
not handle the exception at all,
handle the exception where it occurs, or
handle the exception at another point in the program.
We explore each of these approaches in the following sections.
SELF-REVIEW QUESTIONS (see answers in Appendix N)
SR 11.1 What is the difference between an error and an exception?
SR 11.2 In what ways might a thrown exception be handled?
 
Search WWH ::




Custom Search