Exit Label $EXIT

Rewritten August 2016

If the special label $EXIT: is included in a function or procedure, the EXITFUNCTION statement will transfer to that label, rather than to the physical end of the function—i.e. the ENDFUNCTION statement. This allows you to consolidate cleanup code and/or assignment of the function return value in a single place, and eliminates the common bug of forgetting to assign the return value prior to an EXITFUNCTION statement. For example:    

FUNCTION FN'TEST() AS I4

    open #999, "TEST.LOG", output

    ...

    IF <some condition) EXITFUNCTION

    ...

    ...

$EXIT:

    if eof(999)>=0 close #999

    FN'TEST = <expr>  ! assign return value

ENDFUNCTION

 

In the example above, execution hits the $EXIT label either as the result of the EXITFUNCTION statement, or by just falling into it. This assures that the file is closed and the return value assigned, regardless of which logical path is taken. The one exception would be in the case of a BASIC error, which in the above example, would bypass the $EXIT label. To cover that case, error trapping logic could be added as follows:

FUNCTION FN'TEST() AS I4

    on error goto TRAP

    open #999, "TEST.LOG", output

    ...

    IF <some condition) EXITFUNCTION

    ...

    ...

    EXITFUNCTION   ! skip over error trap

TRAP:

    ...

    RESUME $EXIT

$EXIT:

    if eof(999)>=0 close #999

    FN'TEST = <expr>  ! assign return value

ENDFUNCTION

 

In the modified example above, we added a second EXITFUNCTION to avoid falling into the error trap. The error trap code has the option of resuming explicitly to the $EXIT label, (as in the case above), just like it could resume to any other label within the function. Or it could bypass the $EXIT code with RESUME ENDFUNCTION {WITH_ERROR {N}). See Error Trappingfor more details.

Notes

•   The $EXIT label functions the same way in procedures as in functions, except substituting EXITPROCEDURE and ENDPROCEDURE for EXITFUNCTION and ENDFUNCTION

•   All of the keywords and labels discussed here are case insensitive, including the $EXIT label.

•   Be careful not to include an EXITFUNCTION or EXITPROCEDURE statement within the $EXIT: code, lest you create an infinite loop.

History

2011 July, A-Shell 5.1.1223:  RESUME behavior changed to skip the code following the $EXIT, so as to reduce chance of infinite error trapping loops if an error occurred within that code. Previously, RESUME ENDFUNCTION resumed to the $EXIT label, if present.

2010 September, A-Shell 5.1.1192:  Feature added to A-Shell