Page 613 - Introduction to Programming with Java: A Problem Solving Approach
P. 613
Let’s analyze the error message. First the JVM prints the exception that was thrown, NumberFormatException. Then it prints a call stack trace. A call stack trace is a listing of the meth- ods that were called prior to the crash, in reverse order. What methods were called? First main, then readNumbers, then parseInt. Note the numbers at the right side of the call stack trace. They are the line numbers in the source code for where the methods are called. For example, the 13 in the bottom line says that main’s 13th line is a call to the readNumbers method.
User Immediately Enters q to Quit
At the bottom of the getMean method, note the division operation. Whenever you perform integer divi- sion, you should always be sure to avoid division by zero. In the NumberList program, it’s not avoided. The size instance variable is initialized to zero, and if the user immediately enters q to quit, size stays at zero and getMean performs division by zero. Integer division by zero causes the JVM to throw an ArithmeticException. Since there’s no try-catch mechanism, the JVM prints a detailed error message and terminates the program, like this:
Sample session:
Enter a whole number (q to quit): q
Exception in thread "main"
java.lang.ArithmeticException: / by zero
at NumberList.getMean(NumberList.java:47)
at NumberListDriver.main(NumberListDriver.java:14)
numerator is a positive number, division by 0.0 returns the value Infinity. If the numerator is a negative number, division by 0.0 returns the value -Infinity. If the numerator is also 0.0, division by 0.0 returns the value NaN (for not a number).
User Enters More Than 100 Numbers
In the NumberList program’s instance-variable declarations, note that numList is a 100 element array. In the readNumbers method, note how this statement assigns user-entered numbers into the numList array:
numList[size] = x;
If the user enters 101 numbers, then the size variable increments to 100. That’s bigger than the maximum index (99) in the instantiated array. If you access an array element with an index that’s greater than the maximum index or less than zero, the operation throws an ArrayIndexOutOfBoundsException. Since there are no try and catch blocks, the JVM prints a detailed error message and then terminates the program, like this:
Sample session:
...
Enter a whole number (q to
Enter a whole number (q to
Enter a whole number (q to
Exception in thread "main"
quit): 32
quit): 49
quit): 51
14.11 UnderstandingExceptionMessages 579
Note that if you perform floating-point division with a denominator of zero, there is no exception. If the
Apago PDF Enhancer
java.lang.ArrayIndexOutOfBoundsException: 100
at NumberList.readNumbers(NumberList.java:29)
at NumberListDriver.main(NumberListDriver.java:13)