[Lazarus] exception handling in constructor

Sven Barth pascaldragon at googlemail.com
Sat Mar 2 11:27:37 CET 2013


On 02.03.2013 03:49, Xiangrong Fang 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;

No, this is a bad idea. If an exception occurs inside the constructor 
the destructor will be called automatically. I don't even want to think 
about what bad things could happen if you call Destroy inside the 
constructor...

> I create the objec like:  MyInstance :=
> TMyClass.Create('AnNonExistentFile');  An exception occured, I can
> ensure that:
>
>  1. there is no memory leak.

There won't be a memory leak.

>  2. the MyInstance variable is assigned *nil*?

If you want to ensure that MyInstance is Nil you need to do it like this:

=== code begin ===

try
   MyInstance := TMyClass.Create('AnNonExistentFile');
except
   MyInstance := Nil;
end;

=== code end ===

Regards,
Sven




More information about the Lazarus mailing list