0

According to many tutorials I've read regarding streams and the like, it is considered good practice to close a Stream not inside the try-block, but inside the finally instead, to ensure it's closing with and without an exception.

Of course, this has to be again surrounded by a try-and-catch again, as .close() can throw an IOException. However, as the Javadoc of under what conditions this might happen ("Throws: IOException - if an I/O error occurs.") is extremely vague, I wondered what, specifically, would have to happen for this exception to be thrown at this place. Below is an example code.


FileInputStream fis = null;
try {
    fis = new FileInputStream("C:\\TestFiles\\JapaneseFileNames");
    // Do some stuff
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        if(fis != null) {
            fis.close();
        }
    } catch(IOException e) {
        throw new RuntimeException("Something happened, but what?", e);
    }
}
Adowrath
  • 701
  • 11
  • 24
  • One example of such an exception occurring is if you use a JVM/OS/fs combination which does buffered/optimistic writes and you try and close the descriptor to the file you write to whereas, in reality, there is no space left to write the contents of the file. – fge Nov 12 '15 at 19:50
  • 1
    Anything that needs to write a "footer" when the stream is done. Some compression & crypto streams (e.g. some need to put a hash or so in the end) and I think even `ObjectOutputStream`. (Harddrive can be full, harddrive can have an error, or be unplugged in that moment when it's usb, .. all sorts of IO errors) – zapl Nov 12 '15 at 19:53
  • @fge By that, are you referring to the case of the hard drive or maximum file size being exceeded when the currend buffer would get saved? Because I'm not all too familiar with the terminology here. – Adowrath Nov 12 '15 at 19:54
  • 1
    If using Java 7 or later, you should generally use the try-with-resources statement, which closes the stream and handles the proper handling of the exception for you: http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html. Most of the pain disappears when using it. – JB Nizet Nov 12 '15 at 20:25
  • I'm curious As : did that really happen once ? I mean did someone really got :java.io.IOException :.... on .close() ? – niceman Nov 12 '15 at 21:51

1 Answers1

1
  • If the stream extends FilterOutputStream, the close() method first calls flush(), which may try some I/O and encounter an IOException, which is thrown to the caller of close(). BufferedOutputStream is the typical case.

  • If the stream extends FilterOutputStream and is wrapped around another one, calling close() calls close() on the wrapped stream, which behaves as above. new DataOutputStream(new BufferedOutputStream(...)) and new ObjectOutputStream(new BufferedOutputStream(...)) are typical cases.

user207421
  • 305,947
  • 44
  • 307
  • 483