go to previous page   go to home page   go to next page

Answer:

Yes.


Sample Output

Here is a run of the program. The run encounters an ArrayIndexOutOfBoundsException . The catch block uses getMessage() to print the message in the exception, and then uses printStackTrace().


C:\JavaSource>java IndexPractice
Enter the data:8
Enter the array index:10
This is your problem: 10
Here is where it happened:

java.lang.ArrayIndexOutOfBoundsException: 10
        at IndexPractice.main(IndexPractice.java:18)
Good-by

The stacktrace shows the line on which the exception occured, line 18. That is the number of this line:

value[slot] = data;

The Java virtual machine executes Java bytecodes, not Java source code. However, the bytecode file contains information about how lines of source code and bytecodes correspond. Bytecodes from the Java libraries do not contain line numbers, which is why some of the lines of the stack trace say (Unknown Source).

Here is another run of the program, this time with an InputMismatchException. The InputMismatchException did not contain a message, so its getMessage() method returned a null string.

C:\JavaSource>java IndexPractice
Enter the data:rats
This is your problem: null
Here is where it happened:

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 IndexPractice.main(IndexPractice.java:15)
Good-by

A more sensible program would use a loop to collect data from the user and place it in the array. Exceptions would cause the program to repeat the prompt. This would be much more user-friendly than halting. If a user has entered 999 data items, it would not be friendly to halt the program if item 1000 is wrong!


QUESTION 4:

Why is the stacktrace in the first example shorter than in the second example?


go to previous page   go to home page   go to next page