Java Reference
In-Depth Information
practice to have a
catch
block for each of the specific types of exceptions that a
try
block can throw. That
enables you to indentify and deal with each type of exception individually.
Catching Multiple Exception Types in a Block
You can catch an exception that may be any of two or more different types in a single
catch
block. You
specify the possible types for the
catch
block parameter separated by
|
. Here's a fragment showing how
you do this:
try {
// Code that can throw exceptions
// of type ArithmeticException and ArrayStoreException...
} catch(ArithmeticException|ArrayStoreException e) {
// Code to handle exception of either type...
}
The
catch
block is executed if an exception of either type
ArithmeticException
or type
Ar-
rayStoreException
is thrown in the
try
block. This is particularly useful when you want to handle ex-
ceptions of two or more different types in the same way because it avoids having to write multiple
catch
blocks containing the same code. This can arise quite easily when you call several methods in a single block,
each of which may throw an exception of a different type. When you want to handle more than one type of
exception in the same way, you can use the multiple types form for the
catch
block parameter.
Of course, you can still have multiple
catch
blocks, each of which may respond to one or more exception
types.
The finally Block
The immediate nature of an exception being thrown means that execution of the
try
block code breaks off,
regardless of the importance of the code that follows the point at which the exception was thrown. This in-
troduces the possibility that the exception leaves things in an unsatisfactory state. You might have opened a
file, for example, and because an exception was thrown, the code to close the file is not executed.
The
finally
block provides the means for you to clean up at the end of executing a
try
block. You use a
finally
block when you need to be sure that some particular code is run before a method returns, no matter
what exceptions are thrown within the associated
try
block. A
finally
block is always executed, regard-
less of whether or not exceptions are thrown during the execution of the associated
try
block. If a file needs
to be closed, or a critical resource released, you can guarantee that it is done if the code to do it is put in a
finally
block.
The
finally
block has a very simple structure:
finally {
// Clean-up code to be executed last
}
Just like a
catch
block, a
finally
block is associated with a particular
try
block, and it must be located
immediately following any
catch
blocks for the
try
block. If there are no
catch
blocks then you position
the
finally
block immediately after the
try
block. If you don't do this, your program does not compile.