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 usually do this:
Rationale: If I'm done with the resource and the only problem I have is closing it, there is not much I can do about it. It doesn't make sense either to kill the whole thread if I'm done with the resource anyway.
This is one of the cases when at least for me, it is safe to ignore that checked exception.
To this day I haven't had any problem using this idiom.
One solution, if the two Exceptions are two different classes
But sometimes you cannot avoid this second try-catch. e.g. for closing a stream