Java Reference
In-Depth Information
16
17
System.out.print( "Please enter an integer numerator: " );
18
int numerator = scanner.nextInt();
19
System.out.print( "Please enter an integer denominator: " );
20
int denominator = scanner.nextInt();
21
22
int result = quotient(numerator, denominator);
23
System.out.printf(
24
"%nResult: %d / %d = %d%n" , numerator, denominator, result);
25
}
26
} // end class DivideByZeroNoExceptionHandling
Please enter an integer numerator: 100
Please enter an integer denominator: 7
Result: 100 / 7 = 14
Please enter an integer numerator: 100
Please enter an integer denominator: 0
Exception in thread "main" java.lang.ArithmeticException: / by zero
at DivideByZeroNoExceptionHandling.quotient(
DivideByZeroNoExceptionHandling.java:10)
at DivideByZeroNoExceptionHandling.main(
DivideByZeroNoExceptionHandling.java:22)
Please enter an integer numerator: 100
Please enter an integer denominator: hello
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 DivideByZeroNoExceptionHandling.main(
DivideByZeroNoExceptionHandling.java:20)
Fig. 11.2 | Integer division without exception handling. (Part 2 of 2.)
Stack Trace
The first sample execution in Fig. 11.2 shows a successful division. In the second execu-
tion, the user enters the value 0 as the denominator. Several lines of information are dis-
played in response to this invalid input. This information is known as a stack trace , which
includes the name of the exception ( java.lang.ArithmeticException ) in a descriptive
message that indicates the problem that occurred and the method-call stack (i.e., the call
chain) at the time it occurred. The stack trace includes the path of execution that led to
the exception method by method. This helps you debug the program.
Stack Trace for an ArithmeticException
The first line specifies that an ArithmeticException has occurred. The text after the name
of the exception (“ / by zero ”) indicates that this exception occurred as a result of an at-
tempt to divide by zero. Java does not allow division by zero in integer arithmetic. When
this occurs, Java throws an ArithmeticException . ArithmeticException s can arise from
 
Search WWH ::




Custom Search