Is there an elegant way to handle exceptions that are thrown in finally
block?
For example:
try {
// Use the resource.
}
catch( Exception ex ) {
// Problem with the resource.
}
finally {
try{
resource.close();
}
catch( Exception ex ) {
// Could not close the resource?
}
}
How do you avoid the try
/catch
in the finally
block?
I typically use one of the
closeQuietly
methods inorg.apache.commons.io.IOUtils
:You could refactor this into another method ...
If you can you should test to avoid the error condition to begin with.
Also you should probably only be catching exceptions that you can recover from, if you can't recover then let it propagate to the top level of your program. If you can't test for an error condition that you will have to surround your code with a try catch block like you already have done (although I would recommend still catching specific, expected errors).
If you're using Java 7, and
resource
implementsAutoClosable
, you can do this (using InputStream as an example):Job done. No null tests. Single catch, include acquire and release exceptions. Of course you can use the Execute Around idiom and only have to write it once for each resource type.
Changing
Resource
from best answer toCloseable
Streams implements
Closeable
Thus you can reuse the method for all streams