[DUG] Related try..finally question
Paul Heinz
paul at accredo.co.nz
Fri Jul 21 14:48:06 NZST 2006
James wrote:
> That's an interesting one. I guess you're talking about something
> like this?
>
> Try
> Something := TSomething.Create(nil);
> X := TX.Create(blah); //for some reason crashes here
> Y := TY.Create();
> Finally
> FreeAndNil(Something);
> FreeAndNil(X);
> FreeAndNil(y); //will throw exception (?) because was never created
> End;
>
> If so then you could just
>
> If (something <> nil) then
> FreeAndNil(something);
Umm.. Free already tests against nil and bypasses Destroy if so. The root
problem is calling Free when Y is non-nil as it has not been initialised yet
and thus contains random stack contents. Local variables other than strings
and variants (which are specially handled by the Delphi compiler) are not
initialised to nil or 0 on method entry.
So you need a 'Something := nil; X := nil; Y := nil;' statement block either
just before the Try block (my preference) or immediately inside it. And
remeber to nil the lot, including Something as if it fails inside the
TSomething constructor, Something will still not be initialised yet.
TTFN,
Paul.
More information about the Delphi
mailing list