Java Reference
In-Depth Information
System.out.print("Line 5: Enter the "
+ "divisor: ");
//Line 5
divisor = console.nextInt();
//Line 6
System.out.println();
//Line 7
quotient = dividend / divisor;
//Line 8
System.out.println("Line 9: Quotient = "
+ quotient);
//Line 9
}
}
Sample Run 1:
Line 2: Enter the dividend: 12
Line 5: Enter the divisor: 5
Line 9: Quotient = 2
Sample Run 2:
Line 2: Enter the dividend: 24
Line 5: Enter the divisor: 0
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ExceptionExample1.main(ExceptionExample1.java:22)
Sample Run 3:
Line 2: Enter the dividend: 2e
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at ExceptionExample1.main(ExceptionExample1.java:14)
In Sample Run 1, the value of divisor is nonzero, so no exception occurred. The
program calculated and printed the quotient and terminated normally.
In Sample Run 2, the value entered for divisor is 0 . The statement in Line 8 divides
dividend by the divisor. However, the program does not check whether divisor is 0
before attempting to divide dividend by divisor . So the program terminates with the
message as shown.
In Sample Run 3, the value entered is 2e . This input cannot be expressed as an int
value; therefore, the method nextInt in Line 3 throws an InputMismatchException
and the program terminates with the error message as shown.
1
1
Search WWH ::




Custom Search