Re: different try-finally approach
Mike Schilling wrote:
Bill McCleary wrote:
Mike Schilling wrote:
Bill McCleary wrote:
Mike Schilling wrote:
public static void close(Closeable... c) throws IOException
{
List<IOException> exceptions = new ArrayList<IOException>();
for (Closeable cl : c)
{
try { cl.close()
} catch (IOException ex) {
exceptions.add(ex) }
}
if (exceptions.size() > 0)
throw new WrappedIOException(exceptions);
}
Cute.
Why not
switch (exceptions.size()) {
case 0: return;
case 1: throw exceptions.get(0);
case 2: throw new WrappedIOException(exceptions);
}
Cool. And you can also make the allocation of "exceptions" lazy if
that kind of optimization is important to you.
What? One teensy little ArrayList in what's invariably going to be I/O
bound code? :)
That's my feeling too, but at some point, someone anal is going to
profile it and ask where all those empty ArrayLists came from :-)
Make it (uncompiled, untested)
public final class LinkedListEntry<T>
{
private final T v;
private final LinkedListEntry<T> n;
public LinkedListEntry(final T value, final LinkedListEntry<T> next)
{
v = value;
n = next;
}
public T value()
{
return v;
}
public LinkedListEntry<T> next()
{
return n;
}
}
public static void close(final Closeable... closeables) throws IOException
{
LinkedListEntry<IOException> exceptions = null;
for (final Closeable cl : closeables)
{
try
{
cl.close()
}
catch (final IOException ex)
{
exceptions = new LinkedListEntry<IOException>(ex, exceptions);
}
}
if (exceptions != null)
{
throw new WrappedIOException(exceptions);
}
}
Given that exceptions are intended to be thrown rarely, in exceptional
circumstances, the work for the WrappedIOException ctor to reverse the
order and the overhead of an object per exception should be affordable.
And the LinkedListEntry might come in useful at other places anyway.
Or one could (ab-use) AbstractMap.SimpleImmutableEntry.
--
"I'm a doctor, not a mechanic." Dr Leonard McCoy <mccoy@ncc1701.starfleet.fed>
"I'm a mechanic, not a doctor." Volker Borchert <v_borchert@despammed.com>