Close resource quietly using try-with-resources

后端 未结 3 1510
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-05 02:36

Is it possible to ignore the exception thrown when a resource is closed using a try-with-resources statement?

Example:

class MyResource implements Au         


        
3条回答
  •  时光取名叫无心
    2020-12-05 03:13

    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;
        }
    }
    

提交回复
热议问题