Close resource quietly using try-with-resources

后端 未结 3 1512
佛祖请我去吃肉
佛祖请我去吃肉 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 02:56

    This is one solution:

        boolean ok=false;
        try(MyResource r = new MyResource())
        {
            r.read();
            ok=true;
        }
        catch (Exception e)
        {
            if(ok)
                ; // ignore
            else
                // e.printStackTrace();
                throw e;
        }
    

    If ok==true and we got an exception, it definitely comes from close().

    If ok==false, e comes from read() or constructor. close() will still be called and may throw e2, but e2 will be suppressed anyway.

    The code is quite readable without going through such analysis. Intuitively it says, if ok==true, our real work is done, and we don't really care what errors come after that regarding the resource.

提交回复
热议问题