Reputation: 21966
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.
Upvotes: 1
Views: 107
Reputation: 2952
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);
}
Upvotes: 2
Reputation: 6817
You could add an if condition before closing the stream as follows
if(stream != null) {
stream.close();
}
Upvotes: 1
Reputation: 44808
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();
}
Upvotes: 4