Java Reference
In-Depth Information
{
System.out.print("Line 4: Enter the "
+ "dividend: ");
//Line 4
dividend = console.nextInt();
//Line 5
System.out.println();
//Line 6
System.out.print("Line 7: Enter the "
+ "divisor: ");
//Line 7
divisor = console.nextInt();
//Line 8
System.out.println();
//Line 9
quotient = dividend / divisor;
//Line 10
System.out.println("Line 11: Quotient = "
+ quotient);
//Line 11
}
catch
(Exception eRef)
//Line 12
{
if
(eRef
instanceof
ArithmeticException)
//Line 13
System.out.println("Line 14: Exception "
+ eRef.toString());
//Line 14
else if
(eRef
instanceof
InputMismatchException)
//Line 15
System.out.println("Line 16: Exception "
+ eRef.toString());
//Line 16
}
}
}
This program works the same way as the program in Example 11-3. This program,
however, has only one
catch
block, which can catch all types of exceptions (see the
statement in Line 12). This is because, directly or indirectly, the
class
Exception
is the
superclass of all the exception classes, and a reference variable of a superclass can point to an
object of its subclasses. The parameter
eRef
of the
catch
block in Line 12 is a reference
variable of the
Exception
type. The statement in Line 13 determines whether
eRef
is an
instance of the
class
ArithmeticException
—that is, if it points to an object of the
class
ArithmeticException
. Similarly, the statement in Line 15 determines whether
eRef
is an instance of the
class
InputMismatchException
.If
eRef
is an instance of
ArithmeticException
, then the statement in Line 14 executes, and so on.
1
1
EXAMPLE 11-6
The Student Grade programming example in Chapter 3 calculates a student's grade. It
reads the data from a file and writes the output to a file. The program given in Chapter 3
throws a
FileNotFoundException
and other exceptions. Now that we know how to
handle exceptions in a program, we can rewrite the program to handle the exceptions.
//Program: Calculate the average test score
//This program shows how to handle a FileNotFoundException
//or any other exception.
Search WWH ::
Custom Search