[fpc-pascal] Freeing memory with exceptions

Hairy Pixels genericptr at gmail.com
Tue May 30 15:18:10 CEST 2023

> 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

Ryan Joseph

More information about the fpc-pascal mailing list