Java Reference
In-Depth Information
exception handling technique, namely throwing an exception in a method and catch-
ing it outside the method.
Throwing an Exception in a Method
Sometimes it makes sense to throw an exception in a method but not catch it in the
method. For example, you might have a method with code that throws an exception if
there is an attempt to divide by zero, but you may not want to catch the exception in
that method. Perhaps some programs that use that method should simply end if the
exception is thrown, and other programs that use the method should do something
else. So, you would not know what to do with the exception if you caught it inside the
method. In such cases, it makes sense to not catch the exception in the method defini-
tion, but instead to have any program (or other code) that uses the method place the
method invocation in a
try
block and catch the exception in a
catch
block that fol-
lows that
try
block.
Look at the program in Display 9.9. It has a
try
block, but there is no
throw
state-
ment visible in the
try
block. The statement that does the throwing in that program is
if
(bottom == 0)
throw new
DivisionByZeroException();
This statement is not visible in the
try
block. However, it is in the
try
block in terms
of program execution, because it is in the definition of the method
safeDivide
, and
there is an invocation of
safeDivide
in the
try
block.
The meaning of
throws
DivisionByZero
in the heading of
safeDivide
is discussed
in the next subsection.
Display 9.9
Use of a
throws
Clause
(part 1 of 2)
We will present an even better version
of this program later in this chapter.
1
import
java.util.Scanner;
2
public class
DivisionDemoSecondVersion
3{
4
public static void
main(String[] args)
5
{
6
Scanner keyboard =
new
Scanner(System.in);
7
try
8
{
9
System.out.println("Enter numerator:");
10
int
numerator = keyboard.nextInt();
11
System.out.println("Enter denominator:");
12
int
denominator = keyboard.nextInt();
(continued)