public class DivideByZeroWithExceptionHandling
1: // Fig. 13.2: DivideByZeroWithExceptionHandling.java
2: // An exception-handling example that checks for divide-by-zero.
3: import java.util.InputMismatchException;
4: 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: } // end method quotient
14:
15: public static void main( String args[] )
16: {
17: Scanner scanner = new Scanner( System.in ); // scanner for input
18: boolean continueLoop = true; // determines if more input is needed
19:
20: do
21: {
22: try // read two numbers and calculate quotient
23: {
24: System.out.print( "Please enter an integer numerator: " );
25: int numerator = scanner.nextInt();
26: System.out.print( "Please enter an integer denominator: " );
27: int denominator = scanner.nextInt();
28:
29: int result = quotient( numerator, denominator );
30: System.out.printf( "\nResult: %d / %d = %d\n", numerator,
31: denominator, result );
32: continueLoop = false; // input successful; end looping
33: } // end try
34: catch ( InputMismatchException inputMismatchException )
35: {
36: System.err.printf( "\nException: %s\n",
37: inputMismatchException );
38: scanner.nextLine(); // discard input so user can try again
39: System.out.println(
40: "You must enter integers. Please try again.\n" );
41: } // end catch
42: catch ( ArithmeticException arithmeticException )
43: {
44: System.err.printf( "\nException: %s\n", arithmeticException );
45: System.out.println(
46: "Zero is an invalid denominator. Please try again.\n" );
47: } // end catch
48: } while ( continueLoop ); // end do...while
49: } // end main
50: } // end class DivideByZeroWithExceptionHandling
51:
52:
53: /**************************************************************************
54: * (C) Copyright 1992-2005 by Deitel & Associates, Inc. and *
55: * Pearson Education, Inc. All Rights Reserved. *
56: * *
57: * DISCLAIMER: The authors and publisher of this book have used their *
58: * best efforts in preparing the book. These efforts include the *
59: * development, research, and testing of the theories and programs *
60: * to determine their effectiveness. The authors and publisher make *
61: * no warranty of any kind, expressed or implied, with regard to these *
62: * programs or to the documentation contained in these books. The authors *
63: * and publisher shall not be liable in any event for incidental or *
64: * consequential damages in connection with, or arising out of, the *
65: * furnishing, performance, or use of these programs. *
66: *************************************************************************/