Java Reference
In-Depth Information
Line 5 prompts the user to enter the value of the dividend; the statement in Line 6 stores
this number in the variable
dividend
. The statement in Line 7 prompts the user to enter
the value of the divisor, and the statement in Line 8 stores this number in the variable
divisor
. The statement in Line 9 divides the value of
dividend
by the value of
divisor
and stores the result in
quotient
. The statement in Line 10 outputs the values
of
dividend
,
divisor
, and
quotient
.
The first
catch
block, which starts at Line 11, catches an
ArithmeticException
. The
catch
block that starts at Line 13 catches a
NumberFormatException
.
In Sample Run 1, the program did not throw any exceptions.
In Sample Run 2, the entered value of
divisor
is
0
. Therefore, when the
dividend
is
divided by the
divisor
, the statement in Line 9 throws an
ArithmeticException
,
which is caught by the
catch
block starting at Line 11. The statement in Line 12 outputs
the appropriate message.
In Sample Run 3, the value entered in Line 7 for the variable
divisor
contains the
letter
w
, a nondigit character. Because this value cannot be converted to an integer,
the statement in Line 8 throws a
NumberFormatException
. Note that the
NumberFormatException
is thrown by the method
parseInt
of the
class
Integer
. The
catch
block starting at Line 13 catches this exception, and the statement
in Line 14 outputs the appropriate message.
The program in Example 11-3 uses two
catch
blocks to handle two types of exceptions.
Recall from Chapter 10 that a reference variable of a superclass type can point to the
objects of its subclasses, and using the operator
instanceof
, you can determine whether
a reference variable points to an object of a particular
class
. You can use this facility to
combine the two
catch
blocks of the program in Example 11-3 into one
catch
block, as
shown by the program in Example 11-5.
EXAMPLE 11-5
import
java.util.*;
public class
ExceptionExample5
{
static
Scanner console =
new
Scanner(System.in);
public static void
main(String[] args)
//Line 1
{
int
dividend, divisor, quotient;
//Line 2
try
//Line 3
Search WWH ::
Custom Search