I'm doing some cleanup operations that could throw an exception, and I want to implement the logic of a finally
block, but only if no exceptions are thrown:
The initial implementation is this:
acquireResource();
try {
// stuff
}
catch (Exception e) {
cleanupFromException(e);
throw e;
}
finally {
cleanupTidy();
}
However, if an exception is thrown, this will call cleanupFromException
, then cleanupTidy
(which is what I don't want).
So my next implementation is this:
acquireResource();
try {
// stuff
cleanupTidy();
}
catch (Exception e) {
cleanupFromException(e);
throw e;
}
However, this will not call cleanupTidy
if the code in the try
block does any jumps - return
, continue
, break
, etc - to the outside of the try block.
The best I can come up with is this:
acquireResource();
boolean exceptionThrown = false;
try {
// stuff
}
catch (Exception e) {
exceptionThrown = true;
cleanupFromException(e);
throw e;
}
finally {
if (!exceptionThrown)
cleanupTidy();
}
But this smells a bit whiffy, and is a lot of boilerplate. Is there any better way of having a finally
that only executes if an exception is not thrown (in Java)? Or a way of wrapping this in a simpler API?