try
Foo := TFooBar.Create;
...
finally
Foo.Free;
end;
Consider the above. Suppose that TFooBar.Create raises an exception. In that case the finally block is executed, and `Foo.Free` is called on an uninitialised variable (Foo). That leads to undefined behaviour.
So the correct pattern is
Foo := TFooBar.Create;
try
...
finally
Foo.Free;
end;
Here, if TFooBar.Create raises an exception, the try is never reached, and so the finally block never executes.
Now another pattern was also mentioned
Foo := nil;
try
Foo := TFooBar.Create;
...
finally
Foo.Free;
end;
This is also valid, because Foo is initialised before the try executes. And so in case of constructor exception we would call Free on a nil reference which is fine. However, this pattern is pointless and should be avoided in the scenario here where there is just a single object. It is useful sometimes if there are multiple objects and you want to avoid deep nesting.
A better example of using this pattern is if the object is created conditionally:
Foo := nil;
try
if someTest then
begin
Foo := TFooBar.Create;
...
end;
...
finally
Foo.Free;
end;