That would depend on the purpose of the code inside the finally block. The canonical example is closing a stream after reading/writing from it, some sort of "cleanup" that must be always done. Restoring an object (in this case an iterator) to a valid state IMHO also counts as cleanup, so I see no problem here. If OTOH you were using
return as soon as your return value was found, and adding a lot of unrelated code in the finally block, then it would obscure the purpose and make it all less understandable.
I don't see any problem in using it when "there are no exceptions involved". It's very common to use
try...finally without a
catch when the code can only throw
RuntimeException and you don't plan on handling them. Sometimes, the finally is just a safeguard, and you know for the logic of your program that no exception will ever be thrown (the classic "this should never happen" condition).
Pitfalls: any exception raised inside the
try block will make the
finally bock run. That can put you in an inconsistent state. So, if your return statement were something like:
and this code raised an exception,
fetchNext would still run. OTOH if you coded it like:
T ret = preProcess(next);
next = fetcher.fetchNext(next);
then it would not run. I know you're assuming the try code can never raise any exception, but for cases more complex than this how can you be sure? If your iterator were a long-lived object, that would continue existing even if an unrecoverable error happened in the current thread, than it would be important to keep it in a valid state at all times. Otherwise, it doesn't really matter much...
Performance: it would be interesting to decompile such code to see how it works under the hood, but I don't know enough of the JVM to even take a good guess... Exceptions are usually "exceptional", so the code that handles them don't need to be optimized for speed (hence the advice to never use exceptions in the normal control flow of your programs), but I dunno about