[fpc-pascal] using exceptions

Lars noreply at z505.com
Tue Jan 3 22:20:15 CET 2012


Marcos Douglas wrote:
> On Thu, Dec 22, 2011 at 4:17 PM, Anton Shepelev <anton.txt at gmail.com>
> wrote:
>> Marcos Douglas:
>>
>>> It's  not  difficult,  but is boring have always a
>>> parameter or function return to return  an  error,
>>> and  have  to  verify  if error then... if not er-
>>> ror...  if error and error then... etc
>>

But it is just as boring to write code where you have to check all the
exceptions.  Often I see people using StrToInt without checking that it
was a success.  TryStrToInt allows you to avoid exceptions, so if
exceptions are so good, why do people use trystrtoint and why did borland
create it if delphi is supposed to handle things the exception way? I
think sometimes checking for errors makes the code easier to direct..
except forces you to put the code as if you are using a GOTO except label.

>
> No, I mean is better use try-except than nested IFs/GOTO/etc.

Exceptions are actually GOTO labels.. if you think about what is
happening. If there are any exceptions what happens in your code? You GOTO
the exception area.


>
> Thanks for the tips... but, IMHO, the code above would be more simpler
> like that:
>
> begin
>     Result := False; // Success flag
>     [...]
>     procOne;
>     procTwo;
>     procThree;
>     [...]
>     Result := True;
>   except
>      on e: Exception do
>        ShowMessage(e.Message);
>   end;
> end;
>
> Marcos Douglas


But that just a goto statement going to the except label.. Exceptions in a
way are actually forcing you to write your code in  a GOTO way.

Often you want to handle errors differently, your above code sends it all
to the GOTO except area.. but what if you have to clean up things
depending on the situation? free memory, etc. It's often never as simple
as going to the exception area. It seems easier on the surface to use
exceptions, but when you look into it, it's often not as simple as writing
all code to GOTO exception area...

Is the above code an exception or an error that you are catching? are
errors and exceptions the same thing? Once again, IMO this whole subject
needs to be researched more (academically too). What is the difference,
precisely and rigorously, between an error and exception?  Are exceptions
errors?  If so, why do some people say only to throw an exception when it
is an exception, and use errors for other cases? If that is the case,
exceptions cannot be the same as errors.

In Java exceptions and errors are the same thing, and/or the water is
muddy and it is not clearly defined. In Delphi the water is muddy.  Often
I see people using TryStrToInt instead of StrToInt, which means that
people actually prefer checking the error (false or true) instead of
checking the exception.

Another interesting article is:
http://www.joelonsoftware.com/items/2003/10/13.html





More information about the fpc-pascal mailing list