异常安全返回新对象

当函数返回一个对象时(与使用调用者传入的对象相反 ),请注意异常不会导致对象泄漏。

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;

天真的程序员可能会尝试捕获所有异常类型并从这样的函数返回 nil,但这只是一般情况下阻止所有异常类型而不处理它们的特殊情况。