try-with-resources and null resource
Rémi Forax
forax at univ-mlv.fr
Fri Jan 28 02:03:37 PST 2011
Le 28/01/2011 10:30, Florian Weimer a écrit :
[...]
> 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.
You mean, instead of:
InputStream in = new FileInputStream(path);
try {
useFile(in);
} finally {
in.close();
}
This code is very common. I've spied my students to understand why.
It's because FileInputStream throws an exception so
you put it in the try block, after all try/finally is like try/catch.
Then the IDE warn you that 'in' is not accessible in
the finally block. So you put the declaration on top of the block.
InputStream in;
try {
in = new FileInputStream(path);
useFile(in);
} finally {
in.close();
}
Here the IDE says that 'in' is not initialized if new FileInputStream
throws an exception. So you initialize 'in' to null.
And the IDE warn you because in.close() will throw a NPE.
So you add a null check.
It's the IDE's fault because it should not suggest to initialize 'in'
with null and developer's fault because he blindly follows what the IDE
says.
Rémi
More information about the coin-dev
mailing list