If the code needs to run even when any other code throws an exception, then the finally
block is the correct solution.
If it need not run in the case of an exception (i.e. it’s only necessary for “normal” returns), then using finally
would be abusing the feature.
Personally I’d rewrite that method in the single-return-point style. Not because I religiously subscribe to that idea (I don’t), but because it is best suited for these kind of end-of-method codes.
When that code turns out to be overly complicated (and that’s a very real possibility), then it’s time to refactor the method by extracting one or more methods.
The simplest refactoring would be something like this:
public boolean myMethod() {
boolean result = myExtractedMethod();
/* ... code that must run at end of method ... */
return result;
}
protected boolean myExtractedMethod() {
/* ... code ... */
if(thisCondition) {
return false;
}
/* ... more code ... */
if(thatCondition) {
return false;
}
/* ... even more code ... */
return lastCondition;
}