Embarcadero Delphi Exception-safe return of a new object


Example

When a function returns an object (as opposed to using one that's passed in by the caller), be careful an exception doesn't cause the object to leak.

function MakeStrings: TStrings;
begin
  // Create a new object before entering the try-block.
  Result := TStringList.Create;
  try
    // Execute code that uses the new object and prepares it for the caller.
    Result.Add('One');
    MightThrow;
  except
    // If execution reaches this point, then an exception has occurred. We cannot
    // know how to handle all possible exceptions, so we merely clean up the resources
    // allocated by this function and then re-raise the exception so the caller can
    // choose what to do with it.
    Result.Free;
    raise;
  end;
  // If execution reaches this point, then no exception has occurred, so the
  // function will return Result normally.
end;

Naive programmers might attempt to catch all exception types and return nil from such a function, but that's just a special case of the general discouraged practice of catching all exception types without handling them.