Re: Exception in finally block
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.
This is a part of OP's code. Note that #1 was not defined.
<quote>
try {
.... // code_block: #1
} catch (IOException e) {
....
}
finally {
if (out != null)
out.close();
}
</quote>
This is a part of your previous article.
<quote>
try {
Writer rawOut = ...l;
try {
BufferedWriter out = new BufferedWriter(rawOut);
... // code_block: #2
out.flush();
} finally {
rawOut.close();
}
} catch (IOException exc) {
... // code_block: #3
}
</quote>
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()".
So is that going to be two dialog boxes with cryptic and entirely
unhelpful messages? ;)
Treating the exceptions(*) includes the action of restoring
the instance(*) to the previous state, besides dialog box.
That is,
<code>
Writer rawOut = ...;
try {
BufferedWriter out = new BufferedWriter(rawOut);
...
{code block #4} // XxxxIOException can be thrown.
...
out.close();
}
catch (XxxxIOException e) {
// Restore a related instance of some class to the previous
// state. Or do something that is required.
}
catch (IOException e) {
// dialog box or do something.
}
finally {
try {
rawOut.close();
}
catch (IOException e) {
// process
}
}
</code>
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 ?