typestar

try-finally in Delphi

A TStringList created before the try and freed in the finally, whichever way the function leaves.

program TryFinally;
uses SysUtils, Classes;
// finally runs on every way out: the end, an Exit, or an exception.
function FirstLine(const Text: string): string;
var Lines: TStringList;
begin
  Lines := TStringList.Create;
  try
    Lines.Text := Text;
    if Lines.Count = 0 then
      Exit('(empty)');  // the early exit still passes through finally
    Result := Lines[0];
  finally
    Lines.Free;         // one place holds the cleanup
  end;
end;
begin
  WriteLn(FirstLine('roasted' + sLineBreak + 'ground' + sLineBreak));
  WriteLn(FirstLine(''));
end.

How it works

  1. Lines := TStringList.Create runs first, and the try opens on the line after it.
  2. Exit('(empty)') leaves early, yet Lines.Free in the finally still runs.
  3. The two calls take different paths through FirstLine and both end up freeing the list.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
524
Tokens
102
Three-star pace
75 tpm

At the three-star pace of 75 tokens a minute, this run takes about 82 seconds.

Type this snippet

Step 1 of 3 in Exceptions, step 22 of 27 in Language basics.

← Previous Next →