Is it possible to ignore the exception thrown when a resource is closed using a try-with-resources statement?
Example:
class MyResource implements AutoCloseable{
@Override
public void close() throws Exception {
throw new Exception("Could not close");
}
public void read() throws Exception{
}
}
//this method prints an exception "Could not close"
//I want to ignore it
public static void test(){
try(MyResource r = new MyResource()){
r.read();
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
}
}
Or should I continue to close in a finally
instead?
public static void test2(){
MyResource r = null;
try {
r.read();
}
finally{
if(r!=null){
try {
r.close();
} catch (Exception ignore) {
}
}
}
}
This is one solution:
If
ok==true
and we got an exception, it definitely comes fromclose()
.If
ok==false
,e
comes fromread()
or constructor.close()
will still be called and may throwe2
, 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.I found this answered on the coin-dev mailing list: http://mail.openjdk.java.net/pipermail/coin-dev/2009-April/001503.html
You could use a decorator pattern here to close the resource quietly:
I'm not personally a fan of the resulting syntax, but maybe this works for you:
You can do better if you're willing to limit yourself to dealing with interfaces and leverage a Dynamic Proxy Class:
Then assuming you have:
With an actual resource class:
Calling syntax would look like:
You can do better than this if you want to start including libraries, like AOP enablers. These solutions, however, will work out of the box with JDK7 and no other dependencies.