There are still other things that can go wrong though. If it's an output stream, then close() includes a final flush() of data (e.g. if there's a buffered stream involved along the way) and this may incur a new exception that should
not be swallowed,
unless another exception has already been thrown.
I have deliberately
not included a try/catch for the IOException above, because I don't want to propagate the myth that catching such an exception is the only thing to do. It can be perfectly reasonable to simply declare that your method throws IOException, and let it be caught at a higher level. But if you want to catch and log it locally that can be done. First let's create a utility method:
And then:
Clearly, if you're using
Java 7, it's much, much easier to just use try-with-resources: