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(); } } }
This ensures that all the opened files are properly closed and all the running threads are properly terminated. So, the data in the files will not be corrupted and the user is on the safe-side.
You only need to close streams that use IO resources. From the Stream documentation: Streams have a BaseStream. close() method and implement AutoCloseable , but nearly all stream instances do not actually need to be closed after use.
Don't close in finally block The close method can throw an IOException and FileInputStream / ObjectInputStream can be null. When you use . close in finally , you must check null and try/catch again.
A finally block always executes, regardless of whether an exception is thrown.
Also if you're using Java 7, you can use a try-with-resources statement:
try(BufferedReader r = new BufferedReader(new InputStreamReader(address.openStream()))) { String inLine; while ((inLine = r.readLine()) != null) { System.out.println(inLine); } } catch(IOException readException) { readException.printStackTrace(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With