[fpc-pascal] Fwd: What to do to get new users
Nikolay Nikolov
nickysn at gmail.com
Fri Jan 24 08:01:43 CET 2025
On 1/24/25 8:38 AM, Hairy Pixels via fpc-pascal wrote:
> On Jan 24, 2025 at 1:34:26 PM, Nikolay Nikolov via fpc-pascal
> <fpc-pascal at lists.freepascal.org> wrote:
>> Doesn't matter whether they're handled in the same scope or not. It's
>> the same code. Usually they're not handled in the same scope, but in
>> a very distant place. That's usually when exceptions are convenient.
>> Once you let them bubble up you need to wrap all call sites with
>> try..finally right?
>> Wrong. Only sites that allocate memory, that needs to be freed,
>> before leaving the scope need a try..finally. You don't need to wrap
>> every call. That's nonsense. The pattern is:
>>
>> var
>>
>> {... initialize local vars you're going to allocate in this
>> function with nil}
>>
>> begin
>>
>> try
>>
>> {lots of code, allocations, calls, etc}
>>
>> finally
>>
>> {cleanup code}
>>
>> {free stuff that isn't nil}
>>
>> end;
>>
>> end;
>>
>
> Yes that’s what I meant. If you don't know which calls could fail you
> need to wrap all functions that allocate memory in try..finally.
> That’s what the original post was commenting on, the need for some
> other syntax which knows to free a variable if the function terminates
> early due to an exception, like the implicit exception frames for
> managed types like dynamic arrays.
Yes, that could probably save some typing, however it comes at a price:
1) only works for classes
2) not obvious order of destructor calls. What if they have side
effects, and the order matters?
3) doesn't support procedural APIs.
In really, I find try..finally to be much nicer, because you can do a
proper cleanup in the finally section that includes any of the following:
* destructor calls
* FreeMem
* Dispose
* function calls (e.g. Close(), XFree(), etc.)
And the order is well defined by you.
So, I prefer try..finally. And it's not much typing, when used properly.
Nikolay
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20250124/d935190d/attachment.htm>
More information about the fpc-pascal
mailing list