Ah, correction: the constructor returning
Nil is in most cases caught by the following code accessing the object and which is usually part of a resource protection block:
var
o: TMyClass;
begin
o := TMyClass.Create;
try
o.DoSomething;
finally
o.Free;
end;
end;
Under the assumption that
DoSomething accesses the instance in some way (e.g. VMT call, accessing a field, etc.) this will crash if the constructor returned
Nil, so all is nice and well. And if the constructor decides to raise an exception that is fine as well as the whole resource protection block will be skipped then. What
is problematic however is this:
procedure Test;
var
o: TMyClass;
begin
try
o := TMyClass.Create;
o.DoSomething;
finally
o.Free;
end;
end;
If the constructor raises an exception (which is allowed after all!) this will result in
o having a random value (it's a variable on the stack after all) and thus will result in a nested exception when the code in the
finally block is executed. The solution is to either move the constructor call before the resource protection block or to manually initialize
o to
Nil as the assignment won't be executed if the constructor raises an exception.
However it
is the case that Object Pascal code usually does not check if a valid class instance was returned, relying on the above concepts instead.