Re: different try-finally approach
Mike Schilling wrote:
Bill McCleary wrote:
finally
{
if (foo != null) foo.close()
if (bar != null) bar.close()
if (baz != null) baz.close()
}
}
This is not quite good enough when (as with streams or readers),
"close()" can itself throw.
In actual practice I tend to have a utility method like this somewhere
in a project that uses lots of I/O:
public static void close (Closeable c) {
if (c != null) {
try {
c.close();
} catch (IOException e) {
// Ignore.
}
}
}
which gets rid of the (IMHO useless) close() exceptions, and also allows
nulls (which it ignores).
Then it's
finally {
IOUtils.close(foo);
IOUtils.close(bar);
IOUtils.close(baz);
}
or similarly.
As for the objection that more than one job is being done, maybe, maybe
not. In many cases a single conceptual job involves more than one
stream. For example, copying something out of one file into another
involves working simultaneously with an InputStream and an OutputStream.
These might be wrapped in Reader and Writer, or records from a single
input file might be signal-splittered to several distinct output files,
one for records of type X, one for records of type Y, etc., so there'd
be one InputStream and multiple OutputStreams. Or several input files
are appended -- one of each stream type again, but with the InputStream
being reassigned periodically.