[Lazarus] exception handling in constructor

Howard Page-Clark hdpc at talktalk.net
Sat Mar 2 11:38:57 CET 2013


On 02/03/13 5:45, Flávio Etrusco wrote:
> On Fri, Mar 1, 2013 at 11:49 PM, Xiangrong Fang <xrfang at gmail.com> wrote:
>> Hi there,
>>
>> If my class constructor looks like this:
>>
>> constructor TMyClass.Create(fn: string);
>> begin
>>    sl := TStringList.Create;
>>    try
>>      fs := TFileStream.Create(fn, fmOpenRead);
>>    except
>>      self.Destroy;
>>    end;
>> end;
>>
>> I create the objec like:  MyInstance :=
>> TMyClass.Create('AnNonExistentFile');  An exception occured, I can ensure
>> that:
>>
>> 1. there is no memory leak.
>
> I assume FPC behaves like Delphi, so there's no leak.
> Actually, you don't even need to explicitly call Destroy; when an
> exception occurs in a constructor the destructor is called
> automatically.
>
>> 2. the MyInstance variable is assigned nil?
>
> No, it's not initialized.

But you can write:

constructor TMyClass.Create(fn: string);
var fs: TFileStream;
begin
   sl := TStringList.Create;
   try
     fs := TFileStream.Create(fn, fmOpenRead);
   except
     self:= nil;
   end;
end;

which gives no memory leak, (provided your destructor frees the 
stringlist sl) and also ensures MyInstance is assigned a nil value.





More information about the Lazarus mailing list