I often see the following pattern both in Java documentation and in other people's code when dealing with streams:
FileInputStream fis = null;
try {
fis = new FileInputStream("some.file");
// do something useful with fis
} finally {
if (fis != null) {
fis.close();
}
}
However I personally prefer a different pattern:
FileInputStream fis = new FileInputStream("some.file");
try {
// do something useful with fis
} finally {
fis.close();
}
I like the brevity of the latter and I think it's correct. But am I right about correctness? Is there an objective reason to prefer one over another?
Update
Even if I write the examples pretty much how I would write such code in real life my pattern is still more concise. Compare the documentation approach:
public Object processFile(String fn) throws MyException {
FileInputStream fis = null;
try {
fis = new FileInputStream(fn);
return new Object(); // somehow derived from fis
} catch (FileNotFoundException e) {
throw new MySubExceptionForNotFound(e);
} catch (IOException e) {
throw new MySubExceptionForIoError(e);
} finally {
if (fis != null) {
IOUtils.closeQuietly(fis);
}
}
}
with my approach:
public Object processFile(String fn) throws MyException {
try {
FileInputStream fis = new FileInputStream(fn);
try {
return new Object(); // somehow derived from fis
} finally {
IOUtils.closeQuietly(fis);
}
} catch (FileNotFoundException e) {
throw new MySubExceptionForNotFound(e);
} catch (IOException e) {
throw new MySubExceptionForIoError(e);
}
}
Mine is one line shorter! :D
Interestingly my code does not change if you decide to use fis.close()
instead of IOUtils.closeQuietly()
while the "official" code will grow another 4 lines.