Re: Exception in finally block
Red Orchid wrote:
Thomas Hawtin <usenet@tackline.plus.com> wrote or quoted in
Message-ID: <4572c7eb$0$8758$ed2619ec@ptn-nntp-reader02.plus.net>:
[snip]
My second comment is that the exception from finally should be at least
as significant as the first exception. There shouldn't be much happening
in the finally block. Now, you've switched to a made up example, but the
original, writing to a stream, is common. In that case, if you can't
even close the file you have real problems - at least as bad as not
being able to write to it.
The point of my previous article is that an exception of "finally"
block can discard other exceptions that have to be treated.
As I say, in any sane system, those other exceptions have become
obsoleted by the finally exception.
In #2, it is practicable for an instance(*) of some class to throw
a sub-class exceptions(*) of IOException.
If "rawOut.close()" throws "IOException", the exceptions(*) can
not be treated in #3 although they have to be treated, because
they were swallowed up by the IOException of "rawOut.close()".
Yup, and it's still obsolete.
Treating the exceptions(*) includes the action of restoring
the instance(*) to the previous state, besides dialog box.
Such clean-up actions are required no matter what the exception. So,
they should be in a finally clause, not in a catch clause. It's
generally much easier to work on a copy rather than attempting some roll
back procedure, so such restoring actions are unnecessary.
catch (XxxxIOException e) {
// Restore a related instance of some class to the previous
// state. Or do something that is required.
}
You need this whatever the exception. i.e. it must be in a finally (or
potentially catch Throwable) block (possibly with a boolean to check
whether try block executed successfully).
catch (IOException e) {
// dialog box or do something.
}
finally {
try {
rawOut.close();
}
catch (IOException e) {
// process
Should be the same problem as the previous, or more urgent.
Of course, in #3 of your code, you can roll all the related
instances back. But, to do such policy is to hide problems
that happened. If the policy is valid, why do Java have so
many kinds of exceptions ?
There are different exceptions so that you can diagnose the problem
(possibly). You are going to have fun trying to disentangle multiple
exceptions at once. The most important exception should be the outermost
one.
Tom Hawtin