Dongie Agnir
Dongie Agnir

Reputation: 612

Does close()ing InputStream release resoures even if it throws?

Just a simple question. Given this code:

try {
    // operation on inputstream "is"
} finally {
    try {
        is.close();
    } catch (IOException ioe) {
        //if ioe is thrown, will the handle opened by 'is' be closed?
    }
}

If the close() throws, is the file handle still around (and leaked), or will it have been closed?

Upvotes: 3

Views: 69

Answers (1)

Eric Jablow
Eric Jablow

Reputation: 7889

Not reliably so. If is.close() throws, is might not be marked closed. In any case, there is nothing you can do about it. You don't know the internals of is. The Java 7 equivalent simply hides the problem.

try (InputStream is = Files.newInputStream(...)) {
    // Stuff with is.
} catch (IOException is) {
    ...  // Handles exceptions from the try block.
}  // No finally. Handled by try-with-reources

If the auto-close throws, the exception is a suppressed exception, and you'll never know if or when the file handle is reclaimed.

Upvotes: 3

Related Questions