Is it possible to ignore the exception thrown when a resource is closed using a try-with-resources statement?
Example:
class MyResource implements Au
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.