Java Reference
In-Depth Information
5 3
Enter two integers:
5 / 3 is 1
Enter two integers:
Divisor cannot be zero
5 0
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 14.3 can be rewritten,
as shown in Listing 14.4.
L ISTING 14.4 QuotientWithException.java
1 import java.util.Scanner;
2
3 public class QuotientWithException {
4
5
public static int quotient( int number1, int number2) {
quotient method
if (number2 == 0 )
throw new ArithmeticException( "Divisor cannot be zero" );
throw exception
6
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();
reads two integers
17
int number2 = input.nextInt();
18
19
20
21 System.out.println(number1 + " / " + number2 + " is "
22 + result);
23 }
24
25 System.out.println( "Exception: an integer " +
26
try {
try block
invoke method
int result = quotient(number1, number2);
If an
Arithmetic
Exception
occurs
catch (ArithmeticException ex) {
catch block
"cannot be divided by zero " );
27 }
28
29 System.out.println( "Execution continues ..." );
30 }
31 }
Enter two integers:
5 / 3 is 1
Execution continues ...
5 3
 
 
Search WWH ::




Custom Search