Java Reference
In-Depth Information
End of stack trace output
The output generated for the ArrayIndexOutOfBoundsException is:
Index-out-of-bounds exception caught in divide()
Message in exception object:
3
Stack trace output:
java.lang.ArrayIndexOutOfBoundsException: 3
at TryBlockTest2.divide(TryBlockTest2.java:44)
at TryBlockTest2.main(TryBlockTest2.java:14)
End of stack trace output
How It Works
The 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. You 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.
The message for the arithmetic exception identifies it as being caused by a divide by zero. The message
for the index out of bounds exception is just the invalid index value.
There are a couple of extra println() calls around the call to printStackTrace() to make it easier to
find the stack trace in the output.
The first stack trace, for the arithmetic exception, indicates that the error originated at line 44 in the
source file TryBlockText.java and the last method call was at line 14 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
occurs and how this point in the program is reached.
Standard Exceptions
The majority of predefined exception classes in Java don't provide detailed 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 detailed information is because it can often be gleaned only by prior knowledge of the
computation that is being carried out.
This should spark the glimmer of an idea. If you need more information about the circumstances sur-
rounding an exception, you are going to have to obtain it and, equally important, communicate it to the ap-
propriate point in your program. This leads to the notion of defining your own exceptions.
DEFINING YOUR OWN EXCEPTIONS
There are three basic reasons for defining your own exception classes:
Search WWH ::




Custom Search