try-with-resources and null resource

Jesper Öqvist jesper.oqvist at cs.lth.se
Fri Jan 28 01:55:58 PST 2011


Hi Reinier,

On 2011-01-28 06:50, Reinier Zwitserloot wrote:
> I have a question, and, presupposing either answer, a followup question:
>
> 1. In the above snippet, is t final?
Yes
> 2 if yes: Well, then, calling a method that returns null, such as for
> example Class.getResourceAsStream, is going to be an unbelievable pain. As
> the NPE is then unavoidable, you'd need to assign it to a variable, check
> that variable, and if that variable is not null, start a try block, which
> REQUIRES that you create a NEW variable. urghhhhh!!!!!!! What do I name
> this? out1 and out2? I've got a very big problem with this. even if t is not
> final, I'd have to create a dummy input stream just to have something to
> close.
If Class.getResourceAsStream returns null, it means the resource could 
not be found. In _most_ cases you want to handle this scenario 
explicitly instead of skipping the resource entirely.

If the try with resources-statement would silently ignore that the 
resource was null, then possible errors might go unnoticed by the 
programmer.

I believe that suppressing NPEs just serves to obscure actual problems 
in the handling of your resources.

This whole discussion highlights why programming with null is a bad 
idea, but if we must use null then there should be exceptions whenever 
we try to use null. Java is already a bit confused on this point - in 
some cases null means  "nothing" while in other cases it means 
"invalid/error".

Jesper



More information about the coin-dev mailing list