Java Reference
In-Depth Information
A
catch
block encloses code that is intended to handle exceptions of a particular type that
may be thrown in a
try
block.
❑
The code in a
finally
block is always executed before the method ends, regardless of
whether any exceptions are thrown in the
try
block.
❑
Let's dig into the detail of
try
and
catch
blocks first, then come back to the application of a
finally
block a little later.
The try Block
When you want to catch an exception, the code in the method that might cause the exception to be
thrown must be enclosed in a
try
block. Code that can cause exceptions need not be in a
try
block
but, in this case, the method containing the code won't be able to catch any exceptions that are thrown
and it must declare that it can throw the types of exceptions that are not caught.
A
try
block is simply the keyword
try
, followed by braces enclosing the code that can throw the exception:
try {
// Code that can throw one or more exceptions
}
Although we are discussing primarily exceptions that you must deal with here, a
try
block is also
necessary if you want to catch exceptions of type
Error
or
RuntimeException
. When we come to a
working example in a moment, we will use an exception type that you don't have to catch, simply
because exceptions of this type are easy to generate.
The catch Block
You enclose the code to handle an exception of a given type in a
catch
block. The
catch
block must
immediately follow the
try
block that contains the code that may throw that particular exception. A
catch
block consists of the keyword
catch
followed by a parameter between parentheses that
identifies the type of exception that the block is to deal with. This is followed by the code to handle the
exception enclosed between braces:
try {
// Code that can throw one or more exceptions
} catch(ArithmeticException e) {
// Code to handle the exception
}
This
catch
block only handles
ArithmeticException
exceptions. This implies this is the only kind
of exception that can be thrown in the
try
block. If others can be thrown, this won't compile. We will
come back to handling multiple exception types in a moment.