Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would I care about IOExceptions when a file is closed?

Tags:

java

file

io

I've see this sort of thing in Java code quite often...

try
{
    fileStream.close();
}
catch (IOException ioe)
{
    /* Ignore. We do not care. */
}

Is this reasonable, or cavalier?

When would I care that closing a file failed? What are the implications of ignoring this exception?

like image 430
izb Avatar asked May 13 '09 13:05

izb


People also ask

What causes IOException in Java?

It may occur due to the file deleted or viruses in the file. Sometimes BufferedReader takes data from a network stream where the reading system can fail at any time. So this type of error can occur in input operation when a BufferedReader is used. This is why a buffered reader throws IOException.

How do you handle IOException in Java?

You should put the code for that in a catch or finally clause for the IOException , even if you would like the exception to propagate upwards. If you use a catch clause and you want to propagate it, you will have to rethrow it.

What is IOException in Java?

IOException is the base class for exceptions thrown while accessing information using streams, files and directories. The Base Class Library includes the following types, each of which is a derived class of IOException : DirectoryNotFoundException.


1 Answers

I would at the very least log the exception.

I've seen it happen occasionally, if the attempt to close the file fails due to it not being able to flush the data. If you just swallow the exception, then you've lost data without realizing it.

Ideally, you should probably swallow the exception if you're already in the context of another exception (i.e. you're in a finally block, but due to another exception rather than having completed the try block) but throw it if your operation is otherwise successful. Unfortunately that's somewhat ugly to sort out :(

But yes, you should at least log it.

like image 92
Jon Skeet Avatar answered Nov 06 '22 12:11

Jon Skeet