[fpc-pascal] Freeing memory with exceptions
Michael Van Canneyt
michael at freepascal.org
Thu May 25 08:10:58 CEST 2023
On Thu, 25 May 2023, Hairy Pixels via fpc-pascal wrote:
>> On May 24, 2023, at 8:46 PM, Michael Van Canneyt via fpc-pascal <fpc-pascal at lists.freepascal.org> wrote:
>> I see no problem, I am used to this.
>> This is Pascal, you need to manage your memory and hence your references, this is true even in the absence of exceptions: In your example you would
>> also need to remember to remove your instance from the list after you free
>> it, even if there are no exceptions.
> My example is still not good. The problem I have is that once exceptions
> are used in a program calling any function now has a side effect of
> completely exiting the calling function so you need to be paranoid and
> wrap everything in try blocks just in case. A new added burden for manual
> memory management.
> Why is this better than handling errors as values like a normal function result?
Because it centralizes exit code in case of an error, and allows to have a
In C you need to do something like this:
Function MyFunction(out theresult : TResultType) : Integer;
error condition 1:
Free A, exit (1);
error condition 2:
Free A, Free B, exit(2)
error condition 3:
Free A, Free B, free C, exit(3);
// All went well, report 0
Free A, Free B, free C exit(0);
(you can use a goto, which we all agree on is a bad idea to introduce in a
With exceptions, this becomes
Function MyFunction : TResultType;
I'll take the latter any time.
More information about the fpc-pascal