Java Reference
In-Depth Information
The catch blocks for the outer try block can catch any exceptions that are thrown, but not caught, by
any code within the block, including code within inner try - catch blocks. In the example shown in Figure
7-6 , the catch block for the outer try block catches any exception of type Exception2 . Such exceptions
could originate anywhere within the outer try block. The illustration shows two levels of nesting, but you
can specify more if you know what you're doing.
Rethrowing Exceptions
Even though you may need to recognize that an exception has occurred in a method by implementing a
catch clause for it, this is not necessarily the end of the matter. In many situations, the calling program may
need to know about it — perhaps because it affects the continued operation of the program or because the
calling program may be able to compensate for the problem.
If you need to pass an exception that you have caught on to the calling program, you can rethrow it from
within the catch block using a throw statement. For example:
try {
// Code that originates an arithmetic exception
} catch(ArithmeticException e) {
// Deal with the exception here
throw e; // Rethrow the exception to the calling program
}
The throw statement is the keyword throw followed by the exception object to be thrown. When you
look at how to define your own exceptions later in this chapter, you use exactly the same mechanism to
throw them.
EXCEPTION OBJECTS
Well, you now understand how to put try blocks together with catch blocks and finally blocks in your
methods. You may be thinking at this point that it seems a lot of trouble to go to just to display a message
when an exception is thrown. You may be right, but whether you can do so very much more depends on the
nature and context of the problem. In many situations a message may be the best you can do, although you
Search WWH ::




Custom Search