[fpc-pascal] Freeing memory with exceptions

Sven Barth pascaldragon at googlemail.com
Thu May 25 08:05:46 CEST 2023


Hairy Pixels via fpc-pascal <fpc-pascal at lists.freepascal.org> schrieb am
Do., 25. Mai 2023, 04:32:

>
>
> > 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.
>

I'd say you're over thinking things. The main part is that you protect
locally allocated memory (be it class instances or plain pointers) using
"try... finally" and make sure other memory is for example deallocated in a
destructor. If that's ensured then you can have exceptions bubble up as far
as you're comfortable. E.g. in a LCL application if an exception is raised
somewhere inside an event handler and it isn't explicitly handled there it
will in the end result in a shown error dialog. Assuming all resources
along the way were guarded by resource protection blocks life can just go
on then when the user closes the dialog.

In essence: always protect the resources and only handle an exception
explicitly if you can provide the user with a better error message than
what the exception already provides or have can give them the ability to
correct something.

Why is this better than handling errors as values like a normal function
> result?
>

This would mean that every function (and procedure) that can fail or calls
a routine that can fail would have to provide some kind of error channel
and the user would then have to check this, cluttering their code with
error checks (just look at how correctly error checked code with classic
Pascal I/O looks with all the checks for IOResult).
With exceptions you can simply concentrate on the meaty parts of your
algorithms or business logic and let the language itself deal with the
exceptional (pun intended).

Regards,
Sven
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20230525/43ac673e/attachment.htm>


More information about the fpc-pascal mailing list