try-with-resources and null resource

tom.hawtin at oracle.com tom.hawtin at oracle.com
Fri Jan 28 06:26:22 PST 2011


On 28/01/2011 09:53, Mark Thornton wrote:
> On 28/01/2011 09:30, Florian Weimer wrote:
>>
>> By the way, has anybody else seen this phenomenon in their code base?
>>
>>     InputStream in = null;
>>     try {
>>       in = new FileInputStream(path);
>>       useFile(in);
>>     } finally {
>>       if (in != null) {
>>         in.close();
>>       }
>>     }
>>
>> I'm wondering where this is coming from.

This null-dance pops up frequently in Stack Overflow answers. Drives me 
nuts. The other day someone posted a link to page in the NIO docs where 
something similar is done - only attempting to catch and printf a 
checked exception, but not from the close! Swing locking does something 
similar, only releasing the lock even if the acquire failed.

It seems to be an attempt to "handle" the exception in-method without 
adding another try block and level of indentation.

I believe the old statistic was that two thirds of the finally blocks in 
the Java library are AWOL. So there is some improvement going on!

> In my experience, it arises where you have or might expect to extend to
> cases with more than one resource. You only need one try statement
> instead of a whole nest of them. Once you start doing this for the multi
> resource case I suspect there is a tendency to use the same style for
> single resources as well.

Oh, the classic first failed release skips further releases bug? Usually 
where the code isn't layered well - e.g. acquire driver & connection, 
statement and result set in one polyresponsible blob. I don't think this 
is a cause, because the null dance usually happens in the more common 
simple cases.

Tom



More information about the coin-dev mailing list