REBOL 3 Docs Guide Concepts Functions Datatypes Errors
  TOC < Back Next >   Updated: 8-Apr-2009 Edit History  

REBOL 3 Concepts: Errors: Catching Errors

Pending Revision

This document was written for R2 and has yet to be revised for R3.

The TRY function

You can catch errors with the try function. The try function is similar to the do function. It evaluates a block, but always returns a value, even when an error occurs.

When no error occurs, try returns the value of a block. For example:

print try [100 / 10]

When an error occurs, try returns the error. If you write:

print try [100 / 0]
** Math Error: Attempt to divide by zero.
** Where: 100 / 0

the error is returned from the try and the print function cannot handle it.

To handle errors in a script, you must prevent REBOL from evaluating the error. You can prevent an error from being evaluated by passing it to a function. For instance, the error? function will return true when it is passed an error:

print error? try [100 / 0]

You can also print the datatype of the value returned from a try:

print type? try [100 / 0]

The disarm function converts an error to an error object that can be examined. In the example below, the error variable holds an error object:

error: disarm try [100 / 0]

When an error is disarmed, it will be an object! datatype, not an error! datatype. Evaluating the disarmed object will not cause an error:

probe disarm try [100 / 0]
make object! [
    code: 400
    type: 'math
    id: 'zero-divide
    arg1: none
    arg2: none
    arg3: none
    near: [100 / 0]
    where: none

Error values can be set to a word before they are disarmed. To set a word to an error, it must be preceded by a function that prevents the error from propagating further. For example:

disarm err: try [100 / 0]

Setting a variable enables you to access the value of the block later. The example below will print an error or non-error value:

either error? result: try [100 / 0] [
    probe disarm result
    print result

The ATTEMPT Function

The attempt function can also be used for error handling, but rather than return an error, it returns none when an error occurs.

value: attempt [read %value.r]

The value will be set to none if a read error occurs, normally because the file does not exist.

  TOC < Back Next > - WIP Wiki Feedback Admin