[Lazarus] try finally exit
Hans-Peter Diettrich
DrDiettrich1 at aol.com
Sat Jun 29 16:23:25 CEST 2013
Ludo Brands schrieb:
> As an example consider the following routine:
>
> Procedure Doit (Name : string);
> Var F : Text;
> begin
> Try
> Assign (F,Name);
> Rewrite (name);
> ... File handling ...
> Finally
> Close(F);
> end;
That's a questionable example. Which of the actions are required for
proper operation of Close?
It's much clearer with objects:
MyObj := TMyClass.Create;
//only now the local variable has an valid value
try
//do something with MyObj
finally
MyObj.Free;
end;
Wrong placement of the "try" can result in references to uninitialized
local variables in the "finally" code, with unpredicatable effects.
That's why I prefer to initialize local object variables to Nil, before
entering an try-finally block where they are created. This pattern
allows to use an single try-finally block to protect multiple local objects:
obj1 := nil;
obj2 := nil;
...
try
obj1 := T1.Create;
...
finally
obj1.Free;
obj2.Free;
...
end;
DoDi
More information about the Lazarus
mailing list