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
Lines := TStringList.Createruns first, and thetryopens on the line after it.Exit('(empty)')leaves early, yetLines.Freein thefinallystill runs.- The two calls take different paths through
FirstLineand both end up freeing the list.
Keywords and builtins used here
ExitFirstLineResultWriteLnbeginconstendfinallyfunctionifprogramstringthentryusesvar
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.
Step 1 of 3 in Exceptions, step 22 of 27 in Language basics.