
Home
|


JAVA PROGRAMMING
Exception
Handling Fundamentals
|
What is an Exception?
The term exception is shorthand for the phrase
"exceptional event." It can be defined as follows:
An exception is an event that occurs during the execution of a program
that disrupts the normal flow of instructions.
Many kinds of errors can cause exceptions--problems ranging from serious
hardware errors, such as a hard disk crash, to simple programming errors,
such as trying to access an out-of-bounds array element. When such an
error occurs within a Java method, the method creates an exception object
and hands it off to the runtime system. The exception object contains
information about the exception, including its type and the state of the
program when the error occurred. The runtime system is then responsible
for finding some code to handle the error. In Java terminology, creating
an exception object and handing it to the runtime system is called
throwing an exception.
After a method throws an exception, the runtime system leaps into action
to find someone to handle the exception. The set of possible "someones"
to handle the exception is the set of methods in the call stack of the
method where the error occurred. The runtime system searches backwards
through the call stack, beginning with the method in which the error
occurred, until it finds a method that contains an appropriate exception
handler. An exception handler is considered appropriate if the type of the
exception thrown is the same as the type of exception handled by the
handler. Thus the exception bubbles up through the call stack until an
appropriate handler is found and one of the calling methods handles the
exception. The exception handler chosen is said to catch the exception.
If the runtime system exhaustively searches all of the methods on the call
stack without finding an appropriate exception handler, the runtime system
(and consequently the Java program) terminates.
|
 |