Re: Exception in finally block
Thomas Hawtin <usenet@tackline.plus.com> wrote or quoted in
Message-ID: <45721e2f$0$8748$ed2619ec@ptn-nntp-reader02.plus.net>:
try {
Writer rawOut = ...l;
try {
BufferedWriter out = new BufferedWriter(rawOut);
...
out.flush();
} finally {
rawOut.close();
}
} catch (IOException exc) {
...
}
What is your comment about the following codes ?
<code_0>
try {
try {
throw new Exception("E_0"); // Exception_0
}
finally {
int i = 5;
i /= 0; // Exception_1
}
}
catch (Exception e) {
e.printStackTrace();
}
</code_0>
The "code_0" above prints only "Exception_1". That is,
"Exception_0" is not printStackTraced.
Next,
<code_1>
try {
throw new Exception("E_0"); // Exception_0
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
int i = 5;
i /= 0; // Exception_1
}
catch (Exception e) {
e.printStackTrace();
}
}
</code_1>
The "code_1" above prints both "Exception_0" and "Exception_1".
Last,
<code_2>
void processXX(...) throws IOException {
...
try {
... stream = .....;
// some IOException(*) occurs.
..
}
finally {
stream.close();
}
}
</code_2>
In "code_2" above, if IOException of "stream.close()" occurs,
"IOException(*)" is discarded.
I think that it is better to isolate IOException of "stream.close()"
from other IOExceptions. For example,
<code_3>
void processXX(...) throws IOException, ... {
...
try {
... stream = .....;
// some IOException(*) occurs.
..
}
finally {
try {
stream.close();
}
catch (IOException e) {
// process or throw new IOCloseException(...);
}
}
}
....
class IOCloseException extends Exception {
....
}
</code_3>