Error Trapping in Functions

Updated and November 2016

By default, BASIC errors are internally filtered in such a way that the error appears to the caller to have occurred on the line that called the function. This allows the stack to be properly unwound before doing an unstructured ON ERROR GOTO out of the function. You may, however, create a local error trap inside the function, using the regular ON ERROR GOTO statement. The local error trap may resume back to locations within the function. A new variation of the RESUME statement also allows the local error trap to forward errors to the caller:

RESUME ENDFUNCTION {WITH_ERROR {N}}

Without the optional WITH_ERROR clause, this acts like a normal RESUME LABEL, except that a special reserved virtual label ENDFUNCTION is used to indicate the end of the function. A common way to use this feature would be:

FN'name = err(0)    ! assign basic error # to function value

RESUME ENDFUNCTION  ! return to caller (with error cleared)

 

This would clear the Basic error condition (so it doesn't trigger the caller's ON ERROR GOTO), but it would still return to the caller the error number so that the caller could take action in a more structured manner (as opposed to via an error trap).

If the WITH_ERROR {N} clause is specified, then the function returns, but the current error (or error N, if specified) is set, causing the caller to get an error on the line that called the function. RESUME WITH_ERROR is equivalent to what happens if you don't establish error trapping within the function at all.

Note that since the local error trap code must be within the function, some care must be taken to make sure that it doesn't get executed except on error. One technique would be to use an EXITFUNCTION or EXITPROCEDURE label just above it, for example:

PROCEDURE TEST()

   ON ERROR GOTO TRAP

   ...

   ...

   EXITPROCEDURE

TRAP:

   PRINT "Error #";ERR(0);" in procedure TEST()"

   RESUME ENDPROCEDURE WITH_ERROR 199

ENDPROCEDURE 

 

See Also

•   Call Stack Tracing