Embarcadero Delphi Try-finally with 2 or more objects


Example

Object1 := nil;
Object2 := nil;
try
  Object1 := TMyObject.Create;
  Object2 := TMyObject.Create;
finally
  Object1.Free;
  Object2.Free;
end;

If you do not initialize the objects with nil outside the try-finally block, if one of them fails to be created an AV will occur on the finally block, because the object won't be nil (as it wasn't initialized) and will cause an exception.

The Free method checks if the object is nil, so initializing both objects with nil avoids errors when freeing them if they weren't created.