Java Reference
In-Depth Information
Figure 11.1
Output of the CrashDemo program.
The CrashDemo program crashes when an ArrayIndexOutOfBoundsExcep-
tion occurs, which is an example of a runtime exception. As I mentioned ear-
lier, runtime exceptions are typically the result of programmer error; therefore,
you want the exception to crash your program so you can find and fix the
problem.
Notice from the output in Figure 11.1 of the CrashDemo program that the
following statement does not execute in method2():
System.out.println(“*** Leaving method2 ***”);
This is because the previous statement (shown as follows) causes an
ArrayIndexOutOfBoundsException:
System.out.println(y[5]);
The array referenced by y has only four elements, so three is the largest
index that can be used. This exception is thrown by the JVM, which pops
method2() off the call stack. Because method1() does not do anything with the
exception, method1() is popped off the call stack. Because main() ignores the
exception as well, main() is popped off the call stack.
The exception is then passed on to the JVM, and the JVM prints out the stack
trace before terminating. Notice that the stack trace contains useful informa-
tion, including the line numbers in the source code where the exception
occurred.
You can print this stack trace yourself with any exception you catch by using
the printStackTrace() method of the Throwable class. You will notice that I use
printStackTrace() method in almost every catch block in the examples.
Later in this chapter, I will discuss the Handle or Declare Rule, which
specifies when an exception must be handled. In the earlier CrashDemo
program, if method1() catches the exception and does not throw it again,
the exception is considered handled (no matter what method1() actually
does to fix the problem). If method1() catches the exception and then
Search WWH ::




Custom Search