This is not a standard way. This is a bad way.
I use most of the time:
ObjectOutputStream out = null; try { out = new ObjectOutputStream(new FileOutputStream("file.dat")); // use out } finally { if (out != null) { try { out.close(); } catch (IOException e) { // nothing to do here except log the exception } } }
The code in the finally block can be placed in a helper method, or you can use commons IO to silently close the stream, as indicated in other answers.
In the final block, the stream should always be closed.
Note that JDK7 will greatly simplify the new syntax that will automatically close the stream at the end of the try block:
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("file.dat"))) {
source share