Java Reference
In-Depth Information
an exception to be propagated from the client method to the caller of the client method, and
possibly beyond. A method propagates an exception simply by not including an exception
handler to protect the statement that might throw it. However, for a checked exception, the
compiler requires that the propagating method include a throws clause, even though it does not
itself create and throw the exception. This means that you will sometimes see a method that
has a throws clause but with no throw statement in the method body. Propagation is common
where the calling method is either unable to, or does not need to, undertake any recovery action
itself, but this might be possible or necessary from within higher-level calls. It is also common
in constructors, where a constructor's actions in setting up a new object fail and the constructor
cannot recover from this.
If the exception being propagated is unchecked, then the throws clause is optional, and we pre-
fer to omit it.
12.5.6
The finally clause
A try statement can include a third component that is optional. This is the finally clause
(Code 12.14), and it is often omitted. The finally clause provides for statements that should
be executed whether an exception arises in the protected statements or not. If control reaches
the end of the try block, then the catch blocks are skipped and the finally clause is executed.
Conversely, if an exception is thrown from the try block, the appropriate catch block is executed
and this is then followed by execution of the finally clause.
Code 12.14
A try statement with a
finally clause
try {
Protect one or more statements here.
}
catch (Exception e) {
Report and recover from the exception here.
}
finally {
Perform any actions here common to whether or not
an exception is thrown.
}
At first sight, a finally clause would appear to be redundant. Doesn't the following example il-
lustrate the same flow of control as Code 12.14?
try {
Protect one or more statements here.
}
catch(Exception e) {
Report and recover from the exception here.
}
Perform any actions here common to whether or not an exception is thrown.
 
Search WWH ::




Custom Search