1

Consider this code:

    FileOutputStream stream=null;
    ObjectOutputStream objStr=null;
    try
    {
        stream=new FileOutputStream(defaultFile);
        objStr=new ObjectOutputStream(stream);
        objStr.writeObject(obj);
        objStr.close();
    }
    catch(FileNotFoundException e)
    {
        System.out.println("Il file "+ defaultFile+ " non è stato trovato\n");
    }
    catch(IOException e)
    {
        stream.close();
        System.out.println("Si è verificato un problema di I/O nell' apertura dello  stream");
    }

In the second catch block, I close the stream but I am not sure if it should be closed.
It enters in the second catch if the constructor of ObjectOutputStream fails, but am I sure that in this case, the FileOutputStream remains opened?
Shall I write a finally block to handle all exceptions?
It's hard for me to figure out all cases.

Ramy Al Zuhouri
  • 21,580
  • 26
  • 105
  • 187

3 Answers3

4

If you are using Java 7, you can use the try-with-resources statement to handle all of the closing for you.

try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(defaultFile))) {
    oos.writeObject(obj);
} catch (IOException e) {
    e.printStackTrace();
}
Jeffrey
  • 44,417
  • 8
  • 90
  • 141
2

Add a finally block to your try-catch statement and do the closing there. To avoid another try-catch and a nullcheck in there you can use commons.io IOUtils.closeQuietly():

    FileOutputStream stream = null;
    ObjectOutputStream objStr = null;
    try {
        stream = new FileOutputStream(defaultFile);
        objStr = new ObjectOutputStream(stream);
        objStr.writeObject(obj);
    } catch (FileNotFoundException e) {
        System.out.println("Il file " + defaultFile + " non è stato trovato\n");
    } catch (IOException e) {
        System.out.println("Si è verificato un problema di I/O nell' apertura dello  stream");
    } finally {
        IOUtils.closeQuietly(stream);
        IOUtils.closeQuietly(objStr);
    }      
nansen
  • 2,912
  • 1
  • 20
  • 33
1

You could add an if condition before closing the stream as follows

if(stream != null) {
    stream.close();
}
Chetter Hummin
  • 6,687
  • 8
  • 32
  • 44