[fpc-pascal] Freeing memory with exceptions

Michael Van Canneyt michael at freepascal.org
Tue May 30 16:55:16 CEST 2023



On Tue, 30 May 2023, Hairy Pixels via fpc-pascal wrote:

>
>
>> On May 25, 2023, at 1:10 PM, Michael Van Canneyt via fpc-pascal <fpc-pascal at lists.freepascal.org> wrote:
>>
>>
>> In C you need to do something like this:
>>
>> Function MyFunction(out theresult : TResultType) : Integer;
>>
>> begin
>>  Allocate A
>>  ...
>>  error condition 1:
>>    Free A, exit (1);
>>  ...
>>  Allocate B
>>  error condition 2:
>>    Free A, Free B, exit(2)
>>
>>  Allocate C
>>  error condition 3:
>>   Free A, Free B, free C, exit(3);
>>  ...
>>  // etc
>>  // All went well, report 0
>>  theresult:=X;
>>  Free A, Free B, free C exit(0);
>> end.
>
> Indeed this is an ideal example of why they were invented and it makes sense here. Honestly most of this mess could be cleaned up with smart pointers also and not upset control flow like exceptions do.
>
> I'm doing work with Swift right now and in particular a web framework that makes lots of database calls, all of which can fail so we use exceptions everywhere. The thing that Swift does well and FPC does not, is that it labels the functions as "throws" and calls have a "try" keyword before them so you know how the control flow is actually working.
>
> Because FPC doesn't do this any function could throw errors and thus those stack frames are inserted everywhere and add needless overhead when exceptions aren't used.  It's also nice to not have hidden control flow potential on any function call

The rule is simple in FPC: You should always assume exceptions everywhere.

Simply because system errors are also transformed to exceptions, and thus any function
can indeed throw errors:

an "Access Violation" error can happen on any level of the code,
or an "out of memory" or some other signal by the system or even CPU (think overflow).

If sysutils is used, these are transformed to an exception, regardless of
whether the code itself uses exceptions to report errors or not.

The only way to know for sure there will not be an exception is not to use sysutils
anywhere in your code or anyone elses code.

Delphi introduced a coupling between sysutils and exceptions, and now
we're stuck with that.

Today, you'd need to write your RTL to get rid of them.

Michael.


More information about the fpc-pascal mailing list