Finally blocks are underrated. They’re really very useful for removing duplication in code with multiple exit points. Consider the following:
public int foo(boolean condition1, boolean condition2) {
setMouseBusy();
if (condition1) {
doOne();
setMouseNormal();
return 1;
}
if (condition2) {
doTwo();
setMouseNormal();
return 2;
}
setMouseNormal();
return 0;
}
Compare with this:
public int foo(boolean condition1, boolean condition2) {
try {
setMouseBusy();
if (condition1) {
doOne();
return 1;
}
if (condition2) {
doTwo();
return 2;
}
return 0;
} finally {
setMouseNormal();
}
}
Why is the second form better? Because no matter how the method exits (including throwing exceptions), the finally block will be executed. In the first form, if either of the ‘do’ calls throw an exception the call to setMouseNormal will be skipped, possibly leaving the application with a misleading hourglass cursor.