Java Reference
In-Depth Information
to terminate execution. The main() method's signature contains a throws
clause for Java's ArithmeticException class. The try clause performs the
division operation. If an ArithmeticException error is produced, then ex-
ecution continues in the catch clause; it displays a message followed by
the string returned by the ArithmeticException handler. In this case the
program recovers and prompts the user for another divisor.
Throwing exceptions
The basic rule of Java's error handling mechanism is that an exception must
either be handled by the method in which it is raised, or passed along the
call chain for another method to handle. In this case we say that the excep-
tion has propagated along the call hierarchy. This principle has been de-
scribed by saying that a Java method must either handle or declare all
exceptions.
The declaration of an exception refers to the throws clause that is part
of the method's signature. What this means is that code can refuse to han-
dle a possible exception raised by the method being called. For example,
suppose a call chain consists of methodA(), which calls methodB(),
which calls methodC(). Furthermore, suppose that methodC() can raise
Exception1. In this case methodC() can either handle Exception1 or pass
it along the call chain so that it is handled by methodB(). Here again, if
methodB() does not handle the exception, Java will continue looking up
the call chain for a handler, in this case, in methodA(). Finally, if no han-
dler is found within the application's code, Java will then generate the ex-
ception and terminate execution.
The following program, named Handler.java, demonstrates exception
propagation and handling:
On the Web
The source file for the program Handler.java can be found in the Chap-
ter19folderat www.crcpress.com .
//**********************************************************
//**********************************************************
// Program: Handler
// Reference: Chapter 19
// Topics:
//
1. Propagating exceptions along the call chain
// Requires:
// 1. Keyin class in the current directory
//**********************************************************
Search WWH ::




Custom Search