Java Reference
In-Depth Information
End of stack trace output
The additional output generated for the ArrayIndexOutOfBoundsException will be:
Message in exception object:
null
Stack trace output:
java.lang.ArrayIndexOutOfBoundsException
at TryBlockTest.divide(TryBlockTest.java:54)
at TryBlockTest.main(TryBlockTest.java:17)
End of stack trace output
How It Works
The extra lines of code in each of the catch blocks in the divide() method output the message
associated with the exception object e , by calling its getMessage() method. We could have just put e
here which would invoke the toString() method for e and, in this case, the class name for e would
precede the message. These are a couple of extra println() calls around the call to
printStackTrace() to make it easier to find the stack trace in the output. These are called for the
standard error stream object, System.err , for consistency with the stack trace output.
The first stack trace, for the arithmetic exception, indicates that the error originated at line 54 in the
source file, TryBlockText.java , and the last method call was at line 15 in the same source file. The
second stack trace provides similar information about the index-out-of-bounds exception, including the
offending index value. As you can see, with the stack trace output, it's very easy to see where the error
occurred, and how this point in the program was reached.
Standard Exceptions
The majority of predefined exception classes in Java don't add further information about the conditions
that created the exception. The type alone serves to differentiate one exception from another in most
cases. This general lack of additional information is because it can only be gleaned, in the majority of
cases, by prior knowledge of the computation that is being carried out when the exception occurs, and
the only person who is privy to that is you, since you're writing the program.
This should spark the glimmer of an idea. If you need more information about the circumstances
surrounding an exception, you're going to have to obtain it, and, equally important, communicate it to
the appropriate point in your program. This leads to the notion of defining your own exceptions.
Defining Your Own Exceptions
There are two basic reasons for defining your own exception classes:
You want to add information when a standard exception occurs, and you can do this by
rethrowing an object of your own exception class.
Search WWH ::




Custom Search