Hi,<br><br>Could anyone explain this:<br><br>Number := 123;<br>try<br> Number := Ln(0);<br>except<br>end;<br>WriteLn(Number);<br><br>The output is <b>Nan</b>, 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?<br>
<br>Thanks.<br><br><div class="gmail_quote">2013/3/2 Hans-Peter Diettrich <span dir="ltr"><<a href="mailto:DrDiettrich1@aol.com" target="_blank">DrDiettrich1@aol.com</a>></span><br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
Sven Barth schrieb:<div class="im"><br>
<br>
<blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
If you want to ensure that MyInstance is Nil you need to do it like this:<br>
<br>
=== code begin ===<br>
<br>
try<br>
MyInstance := TMyClass.Create('<u></u>AnNonExistentFile');<br>
except<br>
MyInstance := Nil;<br>
end;<br>
<br>
=== code end ===<br>
</blockquote>
<br></div>
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:<br>
<br>
inst1 := nil;<br>
inst2 := nil;<br>
...<br>
try<br>
inst1 := T1.Create;<br>
inst2 := T2.Create;<br>
...<br>
finally<br>
inst1.Free;<br>
inst2.Free;<br>
...<br>
end;<br>
<br>
The Free does no harm, even if the instances never were created, when the variables are nil'ed before the try block.<br>
<br>
DoDi<div class="HOEnZb"><div class="h5"><br>
<br>
<br>
--<br>
______________________________<u></u>_________________<br>
Lazarus mailing list<br>
<a href="mailto:Lazarus@lists.lazarus.freepascal.org" target="_blank">Lazarus@lists.lazarus.<u></u>freepascal.org</a><br>
<a href="http://lists.lazarus.freepascal.org/mailman/listinfo/lazarus" target="_blank">http://lists.lazarus.<u></u>freepascal.org/mailman/<u></u>listinfo/lazarus</a><br>
</div></div></blockquote></div><br>