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@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
meaningful result.

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.

(you can use a goto, which we all agree on is a bad idea to introduce in a
language)

With exceptions, this becomes

Function MyFunction : TResultType;

begin
  try
    Allocate A
     ..
    allocate B
    ...
    Allocate C
    ...
    Result:=X;
  finally
    free A,B,C
  end;
end.

I'll take the latter any time.

Michael.
_______________________________________________
fpc-pascal maillist  -  fpc-pascal@lists.freepascal.org
https://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-pascal

Reply via email to