try-with-resources and null resource

Rémi Forax forax at univ-mlv.fr
Fri Jan 21 10:28:24 PST 2011


On 01/21/2011 07:24 PM, Paul Benedict wrote:
> The NPE is more useful than the language silently doing nothing with a 
> null pointer. While your idea is convenient, I believe it assumes too 
> much. If anything, perhaps the language shouldn't allow an explicit 
> null assignment in a try-with-resources block.

Hi Paul,
the null assignement is just an example. Perhaps, you prefer this one:

4. try(AutoCloseable c = getAnAutoCloseableThatMayBeNull()) {
5.     // nothing
6. }

Rémi

>
> On Fri, Jan 21, 2011 at 11:12 AM, Rémi Forax <forax at univ-mlv.fr 
> <mailto:forax at univ-mlv.fr>> wrote:
>
>     I think try-with-resources should do a null check before entering
>     in the
>     try block.
>
>     4. try(AutoCloseable c = null) {
>     5.     // nothing
>     6. }
>
>     $ java TryWithresourceNPE
>     Exception in thread "main" java.lang.NullPointerException
>         at TryWithresourceNPE.main(TryWithresourceNPE.java:6)
>
>     I got a NPE from the ends of the try block, I think it will be
>     better to
>     detect the case
>     before entering in the try block like foreach or switch does.
>
>     And with this code:
>
>     5. try(InputStream i = null) {
>     6.       i.available();
>     7. }
>
>     I got the exception below which is not understandable if you don't
>     know
>     how try-with-resources is translated.
>
>     $ java TryWithresourceNPE
>     Exception in thread "main" java.lang.NullPointerException
>         at TryWithresourceNPE.main(TryWithresourceNPE.java:6)
>         Suppressed: java.lang.NullPointerException
>             at TryWithresourceNPE.main(TryWithresourceNPE.java:7)
>
>     If the nullcheck is done before entering in the try block,
>     the exception will be:
>     Exception in thread "main" java.lang.NullPointerException
>         at TryWithresourceNPE.main(TryWithresourceNPE.java:5)
>     which is in my opinion much better.
>
>     Rémi
>     PS: the nullcheck can be done easily by calling getClass() on the
>     expression
>
>     4. try(AutoCloseable c = null) {
>     5.     // nothing
>     6. }
>
>     will be translated to
>
>     aconst_null
>     dup
>     invokevirtual java/lang/Object getClass ()Ljava/lang/Class;
>     astore local_slot_of_c
>
>
>




More information about the coin-dev mailing list