This is a code style question. I notice much example code including some examples from Oracle ensure that a stream is closed in the following manner:
InputStream in = null;
try {
in = acquireStream();
...
} finally {
if (in != null) in.close();
}
Note the initialization to null and check for null in the finally
block.
I tend to write code like this:
InputStream in = acquireStream();
try {
...
} finally {
in.close();
}
Are there advantages or disadvantages to either approach? I like my style because I don't need the null check. Also I like to avoid null
when possible. But since the Oracle style is so common in online examples, I'm wondering if mine has some hidden error.
I ask the same question for InputStream
, OutputStream
, java.sql.Connection
, java.sql.PreparedStatement
, etc. I tend to acquired the resource outside the try
block and then close it in finally
without a null check. Is there anything I am missing other than stylistic differences?
Thanks.