Java Reference
In-Depth Information
Display 9.10
Use of a
throws
Clause
(part 2 of 2)
34
public static void
secondChance()
35 {
36 Scanner keyboard =
new
Scanner(System.in);
37
38
try
39 {
40 System.out.println("Enter numerator:");
41
int
numerator = keyboard.nextInt();
42 System.out.println("Enter denominator:");
43
int
denominator = keyboard.nextInt();
44
double
quotient = safeDivide(numerator, denominator);
45 System.out.println(numerator + "/"
46 + denominator
47 + " = " + quotient);
48 }
49
catch
(DivisionByZeroException e)
50 {
51 System.out.println("I cannot do division by zero.");
52 System.out.println("Aborting program.");
53 System.exit(0);
54 }
55 }
56 }
The input/output dialogues are
identical to those for the program in
Display 9.5.
Declaring Exceptions in a
throws
Clause
If a method does not catch an exception, then (in most cases) it must at least warn
programmers that any invocation of the method might possibly throw an exception.
This warning is called a
throws clause
, and including an exception class in a
throws
clause is called
declaring the exception
. For example, a method that might possibly
throw a
DivisionByZeroException
and that does not catch the exception would
have a heading similar to the following:
throws
clause
declaring an
exception
public void
sampleMethod()
throws
DivisionByZeroException
The part
throws DivisionByZeroException
is a
throws
clause
stating that an
invocation of the method
sampleMethod
might throw a
DivisionByZeroException
.
If there is more than one possible exception that can be thrown in the method definition,
then the exception types are separated by commas, as illustrated in what follows:
throws
clause
public void
sampleMethod()
throws
DivisionByZeroException, SomeOtherException