ON_IOERROR

The ON_IOERROR statement specifies a label to jump to if an I/O error occurs in the current routine. Normally, when an I/O error occurs, an error message is printed and program execution stops. If ON_IOERROR is called and an I/O-related error later occurs in the same routine, control is transferred to the designated statement. The error text and code can then be retrieved from the !ERROR_STATE structure.

The effect of ON_IOERROR can be canceled by using the label “NULL” in the call.

Note: If both ON_IOERROR and CATCH are used in the same routine, I/O errors will always branch to the ON_IOERROR label.

Examples

The following function tries to convert an input to an integer. If the conversion fails, it prints a message and continues processing:

function process_input, arg1in

on_ioerror, bad

arg1 = long(arg1in)

if (0) then begin

bad:

print, !error_state.msg

print, 'defaulting to arg1 = 0'

message, /reset ; make sure to clear our error

on_ioerror, null ; reset error handler

arg1 = 0

endif

; continue with processing...

end

Test the routine:

IDL> a = process_input('hello')

Type conversion error: Unable to convert given STRING to Long.

defaulting to arg1 = 0

Note: In the error handler, we make sure to turn off the error handler for the rest of the routine, to avoid infinite loops.

In this next example, we try to open a file and handle the case of a nonexistent file or read error:

function read_data_file, filename

on_ioerror, bad

data = bytarr(100)

openr, lun, filename, /get_lun

readf, lun, data

close, lun

return, data

bad:

on_ioerror, null ; reset error handler

if (isa(lun)) then free_lun, lun ; close the file

print, !error_state.msg

message, /reset ; make sure to clear our error

return, -1

end

Test the routine:

IDL> a = read_data_file('badname')

OPENR: Error opening file. Unit: 100, File: C:\badname

Note: We make sure to turn off the error handler for the rest of the routine, and we also call free_lun to close the file if a read error occurred.

Syntax

ON_IOERROR, Label

Arguments

Label

Statement to jump to when I/O error is encountered. Use the label NULL to disable the I/O error handler, and return to the normal behavior of halting execution on errors.

Keywords

None.

Version History

Original

Introduced

See Also

CATCH, MESSAGE