Java Reference
In-Depth Information
buck
n. Games. A counter or marker formerly passed from one poker player to
another to indicate an obligation, especially one's turn to deal.
THE AMERICAN HERITAGE DICTIONARY OF THE ENGLISH LANGUAGE,
THIRD EDITION
The buck stops here.
HARRY S TRUMAN
(sign on Truman
'
s desk while he was president)
So far, our examples of exception handling have been toy examples. We have not
yet shown any examples of a program that makes good and realistic use of exception
handling. However, now you know enough about exception handling to discuss
more realistic uses of it. This section explains the single most important exception
handling technique, namely throwing an exception in a method and catching it
outside the method.
Throwing an Exception in a Method
Sometimes it makes sense to throw an exception in a method but not catch it in the
method. For example, you might have a method with code that throws an exception
if there is an attempt to divide by zero, but you may not want to catch the exception
in that method. Perhaps some programs that use that method should simply end if the
exception is thrown, and other programs that use the method should do something
else. So, you would not know what to do with the exception if you caught it inside
the method. In such cases, it makes sense to not catch the exception in the method
definition, but instead to have any program (or other code) that uses the method place
the method invocation in a
try
block and catch the exception in a
catch
block that
follows that
try
block.
Look at the program in Display 9.10. It has a
try
block, but there is no
throw
statement visible in the
try
block. The statement that does the throwing in that
program is
if
(bottom == 0)
throw new
DivisionByZeroException();
This statement is not visible in the
try
block. However, it is in the
try
block in terms
of program execution, because it is in the definition of the method
safeDivide
, and
there is an invocation of
safeDivide
in the
try
block.
The meaning of
throws DivisionByZero
in the heading of
safeDivide
is discussed
in the next subsection.