[Lazarus] exception handling in constructor

Hans-Peter Diettrich DrDiettrich1 at aol.com
Sat Mar 2 12:59:52 CET 2013


Sven Barth schrieb:

> 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 ===

When an exception occurs in Create, the assignment will never take 
place. That's why MyInstance should be set to Nil *before* calling the 
constructor. This also applies to memory leak protection of multiple 
temporary objects:

inst1 := nil;
inst2 := nil;
...
try
   inst1 := T1.Create;
   inst2 := T2.Create;
   ...
finally
   inst1.Free;
   inst2.Free;
   ...
end;

The Free does no harm, even if the instances never were created, when 
the variables are nil'ed before the try block.

DoDi





More information about the Lazarus mailing list