On 1/24/25 8:12 AM, Hairy Pixels via fpc-pascal wrote:
On Jan 24, 2025 at 12:43:51 PM, Nikolay Nikolov via fpc-pascal
<fpc-pascal@lists.freepascal.org> wrote:
That's not what exceptions are meant to be used for, though. What you
describe is called a program "defect". When you encounter a "defect"
in your program, you terminate the program. The proper handling of a
defect is to fix (modify) the program, so it doesn't happen again. In
the case of a "defect", there's no much point in freeing the memory,
because all of the program's memory is freed anyway, when the process
terminates. An exception is used for reporting an unanticipated
condition, encountered at runtime. A program can be correct (bug
free) and still encounter exceptions. For example, a web browser
might encounter a network error, during the loading of a web page, in
which case, it should report the error to the user in its GUI, and it
should continue operating normally, instead of crashing, so the user
can continue browsing, by e.g. trying again, or typing in a different
URL, or switching to a different tab, etc.
Yes I know I’m just saying that’s the most I’ve done with them in
Pascal. I do use them to escape deep recursion too and then they’re
very helpful but I would have random allocations in a recursive that
could fail randomly at any point.
Feels to me like manual memory management and exceptions don’t mix well.
I fail to understand how you came to this conclusion, since I just
showed how the same code would look without exceptions, and it's way
worse.
That example was the best scenario for exceptions where they’re
handled in the same scope they occur and they don’t bubble up through
the call stack.
Doesn't matter whether they're handled in the same scope or not. It's
the same code. Usually they're not handled in the same scope, but in a
very distant place. That's usually when exceptions are convenient.
Once you let them bubble up you need to wrap all call sites with
try..finally right?
Wrong. Only sites that allocate memory, that needs to be freed, before
leaving the scope need a try..finally. You don't need to wrap every
call. That's nonsense. The pattern is:
var
{... initialize local vars you're going to allocate in this function
with nil}
begin
try
{lots of code, allocations, calls, etc}
finally
{cleanup code}
{free stuff that isn't nil}
end;
end;
Nikolay
_______________________________________________
fpc-pascal maillist - fpc-pascal@lists.freepascal.org
https://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-pascal