I want to close my stream in the finally block, but it throws an IOException
so it seems like I have to nest another try
block in my finally
block in order to close the stream. Is that the right way to do it? It seems a bit clunky.
Here's the code:
public void read() {
try {
r = new BufferedReader(new InputStreamReader(address.openStream()));
String inLine;
while ((inLine = r.readLine()) != null) {
System.out.println(inLine);
}
} catch (IOException readException) {
readException.printStackTrace();
} finally {
try {
if (r!=null) r.close();
} catch (Exception e){
e.printStackTrace();
}
}
}
It is. At least java7's try with resources fixes that.
Pre java7 you can make a
closeStream
function that swallows it:Or put the try...finally inside the try catch:
It's more verbose and an exception in the finally will hide one in the try but it's semantically closer to the try-with-resources introduced in Java 7.
Your approach within finally is correct. If the code that you call in a finally block can possibly throw an exception, make sure that you either handle it, or log it. Never let it bubble out of the finally block.
Within the catch block you are swallowing the exception - which is not correct.
Thanks...
source. This sample was useful for me.
Like the answer mentioning the Commons IO library, the Google Guava Libraries has a similar helper method for things which are java.io.Closeable. The class is com.google.common.io.Closeables. The function you are looking for is similarly named as Commons IO: closeQuietly().
Or you could roll your own to close a bunch like this: Closeables.close(closeable1, closeable2, closeable3, ...) :
And that even returns a map of any exceptions that were thrown or null if none were.
In Java 7 you can do this...
AutoCloseable
.close()
called when the try block exits.It's called a Try with resources statement.
Also if you're using Java 7, you can use a try-with-resources statement: