Java Reference
In-Depth Information
Catching one of Java's standard exceptions, as the preceding program does, has a side be-
nefit: It prevents abnormal program termination. When an exception is thrown, it must be
caught by some piece of code, somewhere. In general, if your program does not catch an
exception, then it will be caught by the JVM. The trouble is that the JVM's default ex-
ception handler terminates execution and displays a stack trace and error message. For ex-
ample, in this version of the preceding example, the index out-of-bounds exception is not
caught by the program.
When the array index error occurs, execution is halted, and the following error message
is displayed.
While such a message is useful for you while debugging, it would not be something that
you would want others to see, to say the least! This is why it is important for your program
to handle exceptions itself, rather than rely upon the JVM.
As mentioned earlier, the type of the exception must match the type specified in a catch
statement. If it doesn't, the exception won't be caught. For example, the following program
tries to catch an array boundary error with a catch statement for an ArithmeticException
(another of Java's built-in exceptions). When the array boundary is overrun, an ArrayIn-
dexOutOfBoundsException is generated, but it won't be caught by the catch statement.
This results in abnormal program termination.
Search WWH ::




Custom Search