Java Reference
In-Depth Information
Enter two integers: 5 3
5 / 3 is 1
Enter two integers: 5 0
Divisor cannot be zero
The method
quotient
(lines 4-11) returns the quotient of two integers. If
number2
is
0
, it
cannot return a value, so the program is terminated in line 7. This is clearly a problem. You
should not let the method terminate the program—the
caller
should decide whether to termi-
nate the program.
How can a method notify its caller an exception has occurred? Java enables a method to
throw an exception that can be caught and handled by the caller. Listing 12.3 can be rewritten,
as shown in Listing 12.4.
L
ISTING
12.4
QuotientWithException.java
1
import
java.util.Scanner;
2
3
public class
QuotientWithException {
4
public static int
quotient(
int
number1,
int
number2) {
quotient method
5
if
(number2 ==
0
)
6
throw new
ArithmeticException(
"Divisor cannot be zero"
);
throw exception
7
8
return
number1 / number2;
9 }
10
11
public static void
main(String[] args) {
12 Scanner input =
new
Scanner(System.in);
13
14
// Prompt the user to enter two integers
15 System.out.print(
"Enter two integers: "
);
16
int
number1 = input.nextInt();
read two integers
17
int
number2 = input.nextInt();
18
19
try
{
20
int
result = quotient(number1, number2);
21 System.out.println(number1 +
" / "
+ number2 +
" is "
22 + result);
23 }
24
catch
(ArithmeticException ex) {
25 System.out.println(
"Exception: an integer "
+
26
try
block
invoke method
If an
Arithmetic
Exception
occurs
catch
block
"cannot be divided by zero "
);
27 }
28
29 System.out.println(
"Execution continues ..."
);
30 }
31 }
Enter two integers: 5 3
5 / 3 is 1
Execution continues ...
Search WWH ::
Custom Search