Java Reference
In-Depth Information
Therefore, you should be careful about the order in which you list catch blocks
following a try block (putting more specific exceptions before less specific exceptions).
For example, consider the following sequence of try / catch blocks:
try
//Line 1
{
//statements
}
catch (Exception eRef)
//Line 2
{
//statements
}
catch (ArithmeticException aeRef)
//Line 3
{
//statements
}
Suppose that an exception is thrown in the try block. Because the catch block in Line 2
can catch exceptions of all types, the catch block in Line 3 cannot be reached. This
sequence of try / catch blocks would, in fact, result in a compile-time error. In general, if
a catch block of a superclass appears before a catch block of a subclass, a compilation error
will occur. Therefore, in a sequence of catch blocks following a try block, a catch block
declaring an exception of a subclass type should be placed before catch blocks declaring
exceptions of a superclass type. Often it is useful to make sure that all exceptions that might
be thrown by a try block are caught. In this case, you should make the catch block that
declares an exception of the class Exception type the last catch block.
USING try / catch BLOCKS IN A PROGRAM
Next, we give some examples to illustrate how try / catch blocks might appear in a
program.
As shown in Example 11-1, a common error that might occur while inputting numeric data
is typing a nonnumeric character, such as a letter. If the input is invalid, the methods
nextInt and nextDouble throw an InputMismatchException . Similarly, another error
that might occur when performing numeric calculations is division by zero with integer
values. In this case, the program throws an exception of the class ArithmeticException .
The following program shows how to handle these exceptions.
EXAMPLE 11-3
import java.util.*;
public class ExceptionExample3
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
//Line 1
{
int dividend, divisor, quotient;
//Line 2
Search WWH ::




Custom Search