Close resource quietly using try-with-resources

I found this answered on the coin-dev mailing list:
http://mail.openjdk.java.net/pipermail/coin-dev/2009-April/001503.html

5. Some failures of the close method can be safely ignored (e.g.,
closing a file that was open for read). Does the construct provide for
this?

No. While this functionality seems attractive, it is not clear that
it’s worth the added complexity. As a practical matter these “harmless
exceptions” rarely if ever occur, so a program will be no more robust
if these exceptions are ignored. If you feel you must ignore them,
there is a workaround, but it isn’t pretty:

static void copy(String src, String dest) throws IOException {
    boolean done = false;
    try (InputStream in = new FileInputStream(src)) {
        try(OutputStream out = new FileOutputStream(dest)) {
            byte[] buf = new byte[8192];
            int n;
            while ((n = in.read(buf)) >= 0)
                out.write(buf, 0, n);
        }
        done = true;
    } catch(IOException e) {
        if (!done)
            throw e;
    }
}

Leave a Comment