Java Reference
In-Depth Information
The main() method catches the ZeroDivideException and corrects the element in error by setting its
value to 1. This allows the process to continue. You can see from the output that the ZeroDivideExcep-
tion object has the complete stack trace available, including that relating to the ArithmeticException
and the ArithmeticException message is also there. This is because the ZeroDivideException chains
to the ArithmeticException .
The loop in main() iterates over all the index values for the array. Because divide() references elements
at index+1 and index+2 , ArrayIndexOutOfBoundsException is inevitably thrown in the try block in
divide() . This exception is not rethrown in the catch block and so can never be caught in main() .
WARNING The example has a try-catch block combination inside the loop to en-
able you to see several exceptions being thrown and caught, but this is not a good
idea in practice. Setting up try-catches are resource-intensive, so repeatedly doing
that inside a loop could result in a lot of overhead.
Chains with Multiple Links
The previous example shows two exceptions in a chain, but there are no limitations on this. Where the meth-
od call stack goes through several levels, you can chain as many exceptions together as necessary. You can
access the previous exception to the last exception thrown by calling its getCause() method. You can then
call getCause() for the Throwable reference you have obtained to get the next exception in the chain. You
can repeat this process until getCause() returns null , which signals that you have reach the end of a chain
of exceptions.
SUMMARY
In this chapter you learned what exceptions are and how to deal with them in your programs. You should
make sure that you consider exception handling as an integral part of developing your Java programs. The
robustness of your program code depends on how effectively you deal with the exceptions that can be
thrown within it. Having said that, you should keep in mind that exceptions involve considerable overhead
and should be reserved for very unusual situations. Problems that arise in the normal course of events should
be handled without recourse to throwing exceptions.
EXERCISES
You can download the source code for the examples in the topic and the solutions to the following exer-
cises from www.wrox.com .
Search WWH ::




Custom Search