Embarcadero Delphi Simple try..finally example to avoid memory leaks


Example

Use try-finally to avoid leaking resources (such as memory) in case an exception occurs during execution.

The procedure below saves a string in a file and prevents the TStringList from leaking.

procedure SaveStringToFile(const aFilename: TFilename; const aString: string);
var
  SL: TStringList;
begin
  SL := TStringList.Create; // call outside the try 
  try
    SL.Text := aString;
    SL.SaveToFile(aFilename);
  finally
    SL.Free // will be called no matter what happens above
  end;
end;

Regardless of whether an exception occurs while saving the file, SL will be freed. Any exception will go to the caller.