Java Reference
In-Depth Information
ception handling so that if the user makes a mistake, the program catches and handles (i.e.,
deals with) the exception—in this case, allowing the user to re-enter the input.
1
// Fig. 11.3: DivideByZeroWithExceptionHandling.java
2
// Handling ArithmeticExceptions and InputMismatchExceptions.
3
4
import java.util.InputMismatchException;
import java.util.Scanner;
5
6
public class DivideByZeroWithExceptionHandling
7
{
8
// demonstrates throwing an exception when a divide-by-zero occurs
9
public static int quotient( int numerator, int denominator)
10
throws ArithmeticException
11
{
12
return numerator / denominator; // possible division by zero
13
}
14
15
public static void main(String[] args)
16
{
17
Scanner scanner = new Scanner(System.in);
18
boolean continueLoop = true ; // determines if more input is needed
19
20
do
{
try // read two numbers and calculate quotient
{
System.out.print( "Please enter an integer numerator: " );
int numerator = scanner.nextInt();
System.out.print( "Please enter an integer denominator: " );
int denominator = scanner.nextInt();
int result = quotient(numerator, denominator);
System.out.printf( "%nResult: %d / %d = %d%n" , numerator,
denominator, result);
continueLoop = false ; // input successful; end looping
}
catch (InputMismatchException inputMismatchException)
{
System.err.printf( "%nException: %s%n" ,
inputMismatchException);
scanner.nextLine(); // discard input so user can try again
System.out.printf(
"You must enter integers. Please try again.%n%n" );
}
catch (ArithmeticException arithmeticException)
{
System.err.printf( "%nException: %s%n" , arithmeticException);
System.out.printf(
"Zero is an invalid denominator. Please try again.%n%n" );
}
} while (continueLoop);
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
}
50
} // end class DivideByZeroWithExceptionHandling
Fig. 11.3 | Handling ArithmeticException s and InputMismatchException s. (Part 1 of 2.)
 
Search WWH ::




Custom Search