[Lazarus] Assignment on exception (was Re: exception handling in constructor)

Xiangrong Fang xrfang at gmail.com
Sat Mar 2 14:04:39 CET 2013


Hi,

Could anyone explain this:

Number := 123;
try
  Number := Ln(0);
except
end;
WriteLn(Number);

The output is *Nan*, not 123. i.e. when exception occurs the variable is
modified anyway!  So in the example below assigning MyInstance to nil
before Create does not help to ensure it is nil if an exception occurs?

Thanks.

2013/3/2 Hans-Peter Diettrich <DrDiettrich1 at aol.com>

> 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
>
>
>
> --
> ______________________________**_________________
> Lazarus mailing list
> Lazarus at lists.lazarus.**freepascal.org<Lazarus at lists.lazarus.freepascal.org>
> http://lists.lazarus.**freepascal.org/mailman/**listinfo/lazarus<http://lists.lazarus.freepascal.org/mailman/listinfo/lazarus>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.lazarus-ide.org/pipermail/lazarus/attachments/20130302/bad6a56a/attachment-0002.html>


More information about the Lazarus mailing list