try-with-resources and null resource (original) (raw)
Florian Weimer fweimer at bfk.de
Fri Jan 28 01:30:46 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 ]
- Reinier Zwitserloot:
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 t is not referenced (so its declared type does not matter) and can be null, use a utility method which returns a dummy AutoCloseable instance if the passed argument is null.
If you reference t on some path, you need to generate a dynamic proxy for the null case which throws some suitable exception on all method calls except close(). It's ugly, but it's doable. I don't think it's necessary to have direct support for such an edge case.
By the way, has anybody else seen this phenomenon in their code base?
InputStream in = null; try { in = new FileInputStream(path); useFile(in); } finally { if (in != null) { in.close(); } }
I'm wondering where this is coming from.
-- Florian Weimer <fweimer at bfk.de> BFK edv-consulting GmbH http://www.bfk.de/ Kriegsstraße 100 tel: +49-721-96201-1 D-76133 Karlsruhe fax: +49-721-96201-99
- Previous message: try-with-resources and null resource
- Next message: try-with-resources and null resource
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]