4
votes

I have inherited a large code base that is full of constructs like this:

              try
                 DoWhatever;
              finally
              end;

Sometimes "DoWhatever" involves some fiddling with controls, and very often it's a post to a database, and there are many cases in the code where there IS something in the finally block.

But my understanding is, if there's nothing in the finally block, then the whole try...finally thing is pointless. The code is pretty noisy overall so I'm assuming it was just a placeholder for future code or a holdover from previous code. (There are many placeholders in the code.)

Is my understanding correct or is there some secret double-bluff reverso in Delphi try...finally blocks I've overlooked? (This is Delphi 2010.)

1
No, there is no purpose for an empty finally section (such try..finally block should be removed).Victoria
Thank you for the sanity check. It is much appreciated.user3810626
You're welcome :) For sure, try..finally block makes sense only if there's something to execute (not if it's empty) in the finally section (I would even believe that compiler throws such block away in this case, but that's what I cannot verify now).Victoria
Likely the author of the code doesn't understand try finally. I'd be more concerned about the blocks that have non empty finally sections. I wonder what travesties happen there.David Heffernan
It's possible that the author added it in order to be able to set a breakpoint and inspect the local variables after the call failed. I usually add "asm nop end; in the finally block for that, because I can never remember where to put the breakpoint otherwise.dummzeuch

1 Answers

4
votes

There is no functional purpose to it — it has no effect on the run-time behavior of the program. When control leaves the try section, the program will jump to the finally section, do nothing, and then continue to whatever the next instruction should be (according to how control reached the finally statement), the same as if the try-finally block hadn't been there at all. The only difference will be that the program spends an extra moment before and after the try-finally block as it sets up and clears the control structure form the stack.

It might be that the author had a template that included a try-finally block, but that some instances of that template ended up not needing any cleanup code. Having the code fit a consistent pattern might have made certain automated tasks easier.

The try-finally block might also provide a convenient place to put a breakpoint that triggers after the protected code runs, even in the event of an exception or other premature termination.

To find out why the code has such apparently useless constructs, ask the previous author, or check the commit history.