Java Reference
In-Depth Information
Sample Run 1:
Line 2: Enter the dividend: 12
Line 5: Enter the divisor: 5
Line 10: Quotient = 2
Sample Run 2:
Line 2: Enter the dividend: 24
Line 5: Enter the divisor: 0
Line 11: Cannot divide by zero.
In Sample Run 1, the value of
divisor
is nonzero, so no exception occurred. The
program calculated and printed the quotient and terminated normally.
In Sample Run 2, the value entered for
divisor
is
0
. In Line 8, the program checks
whether
divisor
is
0
. Because
divisor
is zero, the expression in the
if
statement fails
and the
else
part executes, which outputs the third line of the sample run.
Example 11-1 shows what happens when a division by zero or an input mismatch
exception occurs in a program and is not processed. Example 11-2 shows a way to
handle a division by zero exception. However, suppose that division by zero occurs in
more than one place within the same block. In this case, using
if
statements may not be
the most effective way to handle the exception.
Next, we describe how to handle exceptions using Java's exception handling mechanism.
However, first let's note the following.
When an exception occurs, an object of a particular exception
class
is created.
For example, in Sample Run 2 of Example 11-1, an object of the
class
ArithmeticException
is created. Java provides several exception classes to effec-
tively handle certain common exceptions, such as division by zero, invalid input, and
file not found. For example, division by zero is an arithmetic error and is handled
by the
class
ArithmeticException
. Therefore, when a division by zero exception
occurs, the program creates an object of the
class
ArithmeticException
.
Similarly, when a
Scanner
object is used to input data into a program, any invalid
input errors are handled using the
class
InputMismatchException
. Note that the
class
Exception
(directly or indirectly) is the superclass of all the exception classes
in Java.
1
1
Search WWH ::
Custom Search