[Gambas-user] Finally/Catch and Return: How is that meant to be used?

Benoît Minisini benoit.minisini at gambas-basic.org
Thu Sep 14 16:30:19 CEST 2023


Le 14/09/2023 à 16:03, Martin Fischer a écrit :
> Hi all,
> 
> I think I don't understand the approach to error handling gambas has 
> chosen.
> 
> Let's take a simple, very common problem: a function that shall return
> the id (int) of something. To get this id, a looooong and very
> complicated sequence of steps have to be taken. This involves the
> allocation of resources that have to be cleaned up in any case. All
> kinds of errors could happen on the way (errors might get risen).
> 
> Here is pseudocode for this:
> 
> -----------------------
> Public Function getComplicatedId() As Integer
>      Dim result As Integer
> 
>      ' do some very complicated stuff
>      ' resources are allocated on the way. E.g. heap Alloc
> 
>      Return result
> 
> Finally
>      ' clean up resources here
> Catch
>      ' do some logging here
>      Error.Raise("Can't handle this!")
> End
> -----------------------
> 
> The first problem with this code is that the "Return result" causes the
> Finally block to be skipped.
> 
> Moving the "Return result" as last statement into the Finally block does
> work but prevents the Catch block to be executed in case of an error. Bad.
> 
> I'm sure that there is a way to handle cleanup and errors in a clean
> manner (I mean: without Gotos and Labels). I just can't see how to do it
> with Return, Finally and Catch...
> 
> Does anyone have an explanation or example or reference to a
> sample/documentation for this problem?
> 
> Thanks
> 
> __________________________________
> Martin Fischer
> 

The only way to deal with that problem I see is the following:

-----------------------
Public Function getComplicatedId() As Integer
     Dim result As Integer
     Dim bReturn As Boolean

     ' do some very complicated stuff
     ' resources are allocated on the way. E.g. heap Alloc

     bReturn = True

Finally
     ' clean up resources here
     if bReturn Then Return result

Catch
     ' do some logging here
     Error.Raise("Can't handle this!")
End
-----------------------

The interpreter misses a flag local to the function that allows to tell 
that Finally was reached without raising an error.

Regards,

-- 
Benoît Minisini.



More information about the User mailing list