The CATCH procedure provides a generalized mechanism for the handling of exceptions and errors within IDL. Calling CATCH establishes an error handler for the current procedure that intercepts all errors that can be handled by IDL, excluding non-fatal warnings such as math errors.
When an error occurs, each active procedure, beginning with the offending procedure and proceeding up the call stack to the main program level, is examined for an error handler. If an error handler is found, control resumes at the statement after the call to CATCH. The index of the error is returned in the argument to CATCH. The !ERROR_STATE system variable is also set. If no error handlers are found, program execution stops, an error message is issued, and control reverts to the interactive mode. A call to ON_IOERROR in the procedure that causes an I/O error supersedes CATCH, and takes the branch to the label defined by ON_IOERROR.
This mechanism is similar, but not identical to, the
setjmp/longjmp facilities in C and the
catch/throw facilities in C++.
Error handling is discussed in more detail in Controlling Errors.
CATCH, [Variable] [, /CANCEL]
A named variable in which the error index is returned. When an error handler is established by a call to CATCH, Variable is set to zero. If an error occurs, Variable is set to the error index, and control is transferred to the statement after the call to CATCH. The error index is also returned in the CODE field of the
Set this keyword to cancel the error handler for the current procedure. This cancellation does not affect other error handlers that may be established in other active procedures.
The following procedure illustrates the use of CATCH:
PRO CATCH_EXAMPLE ; Define variable A: A = FLTARR(10) ; Establish error handler. When errors occur, the index of the ; error is returned in the variable Error_status: CATCH, Error_status ;This statement begins the error handler: IF Error_status NE 0 THEN BEGIN PRINT, 'Error index: ', Error_status PRINT, 'Error message: ',
!ERROR_STATE.MSG; Handle the error by extending A: A=FLTARR(12) CATCH, /CANCEL ENDIF ; Cause an error: A=12 ; Even though an error occurs in the line above, program ; execution continues to this point because the event handler ; extended the definition of A so that the statement can be ; re-executed. HELP, A END
Running the ABC procedure causes IDL to produce the following output and control returns to the interactive prompt:
Error index: -144 Error message: Attempt to subscript A with <INT ( 11)> is out of range. A FLOAT = Array
Introduced: Pre 4.0
!ERROR_STATE, ON_ERROR, ON_IOERROR, Controlling Errors.