try-with-resources and null resource (original) (raw)
Peter Levart peter.levart at gmail.com
Sat Jan 22 09:10:15 PST 2011
- Previous message: try-with-resources and null resource
- Next message: try-with-resources and null resource
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Perhaps the check for null should be done at cleanup time and do nothing if resource is null. A null value can be considered as a "valid" resource and the cleanup should not throw NPE if this is the case...
Peter
On Saturday, January 22, 2011 02:09:31 pm Rémi Forax wrote:
On 01/21/2011 08:38 PM, Joe Darcy wrote: > Rémi Forax 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) > > I'm not too concerned about that stacktrace since the primary > exception points to the right location.
But the suppressed exception occurs in a generated code that the user don't write. I don't like the idea that a user mistake blow up in a generated code, try-with-resources should protect itself. http://www.google.com/search?q=Throw+early+catch+late >> 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 >> >> aconstnull >> dup >> invokevirtual java/lang/Object getClass ()Ljava/lang/Class; >> astore localslotofc > > Yes, javac internal uses that idiom for null checks and the JVM knows > how to optimize this well :-) > > -Joe Rémi
- Previous message: try-with-resources and null resource
- Next message: try-with-resources and null resource
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]