Error Trapping

Error traps let you intercept and deal with run-time errors, rather than having programs unceremoniously abort or ignore a fatal error, possibly causing loss of data.

There are three steps you must take to trap errors, as described in the following sections:

  1. Set the error trap.  Use the ON ERROR GOTO statement.

  2. Write the error-handling routine.  The error-handling routine receives control when an error occurs.

  3. Exit the error-handling routine.  You exit the error handler using the RESUME statement so execution can continue at an appropriate location in the code.

For example, here is a piece of code that fills an array with the filenames from a directory.  This section will add complete Error Trapping to prevent run-time errors when the user chooses a directory that does not have any files or a drive that is not ready.

SUB GetFileNames(File() AS STRING)

  DIM CurrentDir AS STRING

  DIM fName AS STRING, Mask AS STRING

  DIM X AS INTEGER

 

  Mask = "*.*"

  CurrentDir = CURDIR$

  Path  = AskUserForPath$()

  fName = DIR$(RTRIM$(Path) + Mask)

  IF LEN(fName) = 0 THEN EXIT SUB

  X = 1

 

  WHILE LEN(fName)

    Files(X) = fName

    fName = DIR$

    INCR X

  WEND

END SUB

 

See Also

Error Overview

How error traps work

Setting an error trap

Writing an error handler

Exiting an error handler

Error Trapping Summary