// Catches both SuperException and SubException
} catch (SubException subRef) {
// This would never be reached
}
}
}
Only one exception is handled by any single encounter with a TRy clause. If a catch or finally clause
throws another exception, the catch clauses of the try are not reexamined. The catch and finally
clauses are outside the protection of the try clause itself. Such exceptions can, of course, be handled by any
encompassing try block in which the inner catch or finally clauses were nested.
12.4.1. finally
The finally clause of a try statement provides a mechanism for executing a section of code whether or
not an exception is thrown. Usually, the finally clause is used to clean up internal state or to release
non-object resources, such as open files stored in local variables. Here is a method that closes a file when its
work is done, even if an error occurs:
public boolean searchFor(String file, String word)
throws StreamException
{
Stream input = null;
try {
input = new Stream(file);
while (!input.eof())
if (input.next().equals(word))
return true;
return false; // not found
} finally {
if (input != null)
input.close();
}
}
If the new fails, input will never be changed from its initial null value. If the new succeeds, input will
reference the object that represents the open file. When the finally clause is executed, the input stream
is closed only if it has been open. Whether or not the operations on the stream generate an exception, the
contents of the finally clause ensure that the file is closed, thereby conserving the limited resource of
simultaneous open files. The searchFor method declares that it throws StreamException so that any
exceptions generated are passed through to the invoking code after cleanup, including any
StreamException thrown by the invocation of close.
There are two main coding idioms for correctly using finally. The general situation is that we have two
actions, call them pre and post, such that if pre occurs then post must occurregardless of what other
actions occur between pre and post and regardless of whether those actions complete successfully or throw
exceptions. One idiom for ensuring this is:
pre();
try {
// other actions
} finally {
post();
}