Java Reference
In-Depth Information
this happens when
in.close
is called, the exception prevents
out.close
from getting called, and
the output stream remains open.
Note that this program violates the advice of
Puzzle 36
: The calls to
close
can cause the
finally
block to complete abruptly. Unfortunately, the compiler doesn't help you find the problem, because
close
throws the same exception type as
read
and
write
, and the enclosing method (
copy
) is
declared to propagate it.
The solution is to wrap each call to
close
in a nested
try
block. The following version of the
finally
block is guaranteed to invoke
close
on both streams:
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ex) {
// There is nothing we can do if close fails
}
}
if (out != null) {
try {
out.close();
} catch (IOException ex) {
// Again, there is nothing we can do if close fails
}
}
}
As of release 5.0, you can refactor the code to take advantage of the
Closeable
interface:
Search WWH ::
Custom Search