If you have a cleanup code to run regardless of whether an exception has been thrown, try { ... } finally { ... }this is what you need. But what if you want this cleanup code to be executed only in case of an exception?
One possible solution is to:
boolean ok = false;
try {
doWork();
ok = true;
} finally {
if (!ok) {
doCleanup();
}
}
He does exactly what I want, but I wondered if there was a more natural way to express the idea.
This alternative fails:
try {
doWork();
} catch (Throwable e) {
doCleanup();
throw e; // BAD: Cant do this unless the enclosing function is declared to throw Throwable
}
I suppose I could use Exception instead of Throwable, but I don't like the idea that a non-Exception throwable will bypass the cleanup code. After all, the regular block finallystill works even for non-exceptions.
Also: in C ++, you simply use the catch-all block:
try {
doWork();
} catch (...) {
doCleanup();
throw;
}