try-with-resources and null resource

Bruce Chapman brucechapman at paradise.net.nz
Wed Jan 26 01:23:50 PST 2011


On 25/01/2011 10:57 p.m., Tomasz Kowalczewski wrote:
> What if null is an expected (though maybe unwelcome) value and I want
> to do something with it inside try-with-resources:
>
> ClassLoader classLoader = ...;
> try(InputStream in = classLoader.getResourceAsStream("foo")) { // may
> return null
>
> if(in == null) {
> //let's fallback to some other resource searching scheme.
> }
>
> }
>
> My understanding is that 'in' is implicitly final and I cannot write
> any fallback code.
'in' is implicitly final  but fallback can be done - see below.
> When the resource is null I have no way of leaving
> the t-w-r block without generating exception.
That is correct. Maybe null resources should have close() skipped - that 
way it is up to you.

> I cannot do:
>
> if(in == null) {
> in = new FakeInputStreamOrSomething();
> }
>
> or:
>
> if(in == null) {
> in = classLoader.getResourceAsStream("some other resource");
> }
>
> Of course I can do a proper null-checking logic before going into t-w-r:
>
> ClassLoader classLoader = ...;
> InputStream in = classLoader.getResourceAsStream("foo")
>
> if(in == null) {
> in = // fallback resource loading...
> }
>
> try(InputStream in2 = in) {
> }
>
> But that's still ugly.

I'd solve most of this problem by putting the primary and fallback 
resource finding logic in a separate method and call that method as the 
resource initializer expression. However, as you said, that will still 
cause the t-w-r to always NPE if you cannot find any resource so return 
null.  'Always NPE on null' stops you from coding this in any way 
approaching a nice form. - unless of course null didn't NPE from any of 
the t-w-r implementation/background code, only from the block. That 
option might be worth further consideration.

Bruce

> Thanks for listening,
> Tomek
>




More information about the coin-dev mailing list