try-with-resources and null resource

David Holmes David.Holmes at oracle.com
Thu Jan 27 22:38:33 PST 2011


Tim Peierls said the following on 01/28/11 00:47:
> I don't know about C#, but I like the formulation that can be sloppily
> summarized as "t-w-r calls close on non-null resources".

So to summarize there are three potential candidates for:

try (Resource r = getResource() {
   // stuff here
}

I'm ignoring the suppressed exception aspects for simplicity:

a) Simple transformation into try-finally (current implemented semantics)

   Resource r = getResource();
   try {
     // stuff here
   }
   finally {
     r.close();
   }

b) Transformation into try-finally with explicit null-check on entry

   Resource r = getResource();
   Objects.requireNonNull(r); // heh heh - couldn't resist!
   try {
     // stuff here
   }
   finally {
     r.close();
   }

c) Simple transformation into try-finally but only close a non-null resource

   Resource r = getResource();
   try {
     // stuff here
   }
   finally {
     if (r != null)
       r.close();
   }


Option (a) is, perhaps, the most consistent with preserving the 
behaviour of current code that would be modified to use the new 
construct. This construct will be taught by analogy as it is the only 
effective way to explain things "try-with-resources behaves as-if you 
had written ....". That said I think existing code would have an 
explicit null-check to avoid the try-finally in the null case. And I 
think it is potentially risky to execute the try block only to have NPE 
thrown later.

Option (c) seems appealing in some sense because there's no NPE's at all 
if you don't use "r", but I think that appeal is superficial. To me the 
fundamental question to ask is: what is try-with-resources for? And I 
believe the answer to that is to initialize, use and then clean-up an 
AutoCloseable object. So to me using try-with-resource on a resource 
that might be null is simply a mis-use of try-with-resources: if it can 
be null you can't autoclose it, so trying to is a programming error and 
programming errors should be detected and reported as early as possible. 
So to me option (b) is the preferred semantics for this new construct.

David Holmes



More information about the coin-dev mailing list