The correct way is to have A
take ownership of B
and let A
's destructor free B
. That way, your exception handler only as to worry about freeing A
, and it will free B
if it was created before the exception was raised.
type
ClassA = class
public
B: ClassB;
destructor Destroy; override;
end;
destructor ClassA.Destroy;
begin
B.Free;
inherited;
end;
var
A: ClassA;
begin
...
A := ClassA.Create;
try
...
A.B := ClassB.Create;
...
except
on e: Exception do
begin
FreeAndNil(A); // or A.Free;
...
end;
end;
...
end;