異常安全返回新物件

當函式返回一個物件時(與使用呼叫者傳入的物件相反 ),請注意異常不會導致物件洩漏。

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,但這只是一般情況下阻止所有異常型別而不處理它們的特殊情況。