[fpc-pascal] Fwd: What to do to get new users

Nikolay Nikolov nickysn at gmail.com
Fri Jan 24 05:20:02 CET 2025


On 1/24/25 4:04 AM, Hairy Pixels via fpc-pascal wrote:
> On Jan 24, 2025 at 8:38:25 AM, Nikolay Nikolov via fpc-pascal 
> <fpc-pascal at lists.freepascal.org> wrote:
>> Maybe because there's a much better way to write it:
>>
>> procedure foo();
>> var
>>   s1: TStringList = nil;
>>   s2: TStringList = nil;
>>   s3: TStringList = nil;
>> begin
>>   try
>>     s1:=TStringList.create;
>>     s2:=TStringList.create;
>>     s3:=TStringList.create;
>>     doWhatever(s1,s2,s3);
>>   finally
>>     FreeAndNil(s3);
>>     FreeAndNil(s2);
>>     FreeAndNil(s1);
>>   end;
>> end;
>>
>> Best regards,
>>
>> Nikolay 
>
> I’ve basically never used try..finally in  my own code but I have seen 
> really ugly nested like about in other projects.
Then your code will probably cause memory leaks in case of exceptions, 
and even worse - leaks of other resources (file handles, sockets, etc.).
> This a down stream consequence of exceptions right?

That's a downstream consequence having error handling with proper 
cleanup, regardless of whether the language uses exceptions, or not. 
Consider the case, without exceptions, as is typical for procedural APIs:

function foo: LongInt;

var

   s1, s2, s3: TStringList;

begin

   s1 := Create_StringList;

   if s1=nil then

   begin

     Result := error;

     exit;

   end;

   s2 := Create_StringList;

   if s2=nil then

   begin

     Free_StringList(s1);

     Result := error;

     exit;

   end;

   s3 := Create_StringList;

   if s3=nil then

   begin

     Free_StringList(s1);

     Free_StringList(s2);

     Result := error;

     exit;

   end;

   if not doWhatever(s1, s2, s3) then

   begin

     Free_StringList(s1);

     Free_StringList(s2);

     Free_StringList(s3);

     Result := error;

     exit;

   end;

   {...etc.}

   Free_StringList(s1);

   Free_StringList(s2);

   Free_StringList(s3);

end;

As you can see, it's more complicated and more error prone. You can 
simplify it a little bit with goto, but it will never be better, 
compared to try...finally

Best regards,

Nikolay
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20250124/9e620d81/attachment.htm>


More information about the fpc-pascal mailing list