Partilhar via


Procedural Error Handling

You can detect and handle errors in a single or multiple lines of code by using the ON ERROR command and specifying any valid command or expression. However, you typically use the DO command to specify an error-handling procedure or program. Typically, you use ON ERROR as the overall error handler in your application for those errors that more local error handlers, such as Error events and TRY...CATCH...FINALLY, do not handle.

For example, suppose you have the following invalid line of code in a program (.prg) file:

qxy

When you run the program, Visual FoxPro displays the appropriate error message, "Unrecognized command verb." However, you can create an ON ERROR routine to detect this invalid command and run a procedure or program that handles this error. The following lines of code precede the invalid command with the ON ERROR command, which includes the ERROR( ) function and display the results using the ? command:

ON ERROR ?ERROR()
qxy

When these lines of code run, the ON ERROR command detects the error and displays the error number returned by the ERROR( ) function for the error message, "Unrecognized command verb", in the active output window instead of the error message itself.

In its basic form, the following code illustrates an ON ERROR routine:

LOCAL lcOldOnError
lcOldOnError = ON("ERROR") && Save default error handler.

* Call ON ERROR with an error procedure. 
ON ERROR DO ErrHandler WITH ERROR(), MESSAGE() 

* Insert code that error handling routine applies to.

* Reset original error handler.
ON ERROR &lcOldOnError

PROCEDURE ErrHandler
   LOCAL aErrInfo[1]
   AERROR(aErrInfo)
   DO CASE
      CASE aErrInfo[1] = ErrorNum && Specify appropriate error number.
         * Display appropriate message and insert code to fix error.
      OTHERWISE
         * Display generic message. 
ENDPROC

For more information, see ON ERROR Command. You can also include other error handlers, such as TRY...CATCH...FINALLY in procedural code.

See Also

Reference

Debugging and Error-Handling Language

Concepts

Structured Error Handling
Class and Object Error Handling
Handling Run-Time Errors