Pacerier
Pacerier

Reputation: 89763

Are streams closed automatically on error?

Hi all I understand that if we read bytes from an InputStream and we have finished reading all the bytes (or we do not intend to read to the end of stream), we must call close() to release system resources associated with the stream.

Now I was wondering if I read bytes and it throws a java.io.IOException, am I still required to call close() to release system resources associated with the stream?

Or is it true that on errors, streams are closed automatically so we do not have to call close() ?

Upvotes: 5

Views: 1255

Answers (1)

TC1
TC1

Reputation: 1

The OS itself might close the streams and deallocate resources because the process (namely, the JVM) terminates, but it is not mandated to do so.

You should always implement a finally block where you close it in cases like these, e.g. like this:

InputStream is = null;

try {
    is = new FileInputStream(new File("lolwtf"));
    //read stuff here
} catch (IOException e) {
    System.out.println("omfg, it didn't work");
} finally {
    is.close();
}

This isn't really guaranteed to work if it threw in the first place, but you'll probably wanna terminate at that point anyway since your data source is probably messed up in some way. You can find out more info about it if you keep the InputStream's provider around, like, if I kept a ref to the File object around in my example, I could check whether it exists etc via File's interface, but that's specific to your particular data provider.

This tactic gets more useful with network sessions that throw, e.g., with Hibernate...

Upvotes: 6

Related Questions