Java Reference
In-Depth Information
// Invalid catch block sequence - won't compile!
try {
// try block code
} catch(Exception e) {
// Generic handling of exceptions
} catch(ArithmeticException e) {
// Specialized handling for these exceptions
}
Of course, this won't get past the compiler - it would be flagged as an error.
To summarize - if you have
catch
blocks for several exception types in the same class hierarchy, you
must put the
catch
blocks in order, starting with the lowest subclass first, and then progressing to the
highest superclass.
In principle, if you're only interested in generic exceptions, all the error handling code can be localized in
one
catch
block for exceptions of the superclass type. However, in general it is more useful, and better
practice, to have a
catch
block for each of the specific types of exceptions that a
try
block can throw.
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
introduces the possibility that the exception leaves things in an unsatisfactory state. You might have opened a
file, for instance, 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 previous
try
block. A
finally
block is
always executed, regardless of what happens during the execution of the method. If a file needs to be
closed, or a critical resource released, you can guarantee that it will be 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
will not compile.