How to properly handle an IOException from close()

前端 未结 9 1560
滥情空心
滥情空心 2021-02-05 08:14

The Java I/O classes java.io.Reader, java.io.Writer, java.io.InputStream, java.io.OutpuStream and their various subclasses al

9条回答
  •  孤城傲影
    2021-02-05 08:35

    Generally resource handling should look like this:

    final Resource resource = context.acquire();
    try {
        use(resource);
    } finally {
        resource.release();
    }
    

    In (the unlikely) case of release throwing an exception, any exception thrown by use will be dropped. I don't have a problem with the exception thrown closest to the catcher winning. I believe ARM blocks in JDK7(?) will do something crazy in this case, like rethrowing the use exception with the release exception attached.

    If you use the Execute Around idiom, you can put these decisions and potentially messy code in one (or few) places.

提交回复
热议问题