Example

Trapping Errors

Author: Carl Sassenrath
Return to REBOL Cookbook

Trapping errors in REBOL is easy. There are two standard functions for trapping errors: TRY and ATTEMPT.

Here is an example of the TRY function:


    if error? try [
        data: read %file.txt
    ][
        print "Error reading file.txt"
    ]

TRY evaluates the block and returns its value or an error object. The ERROR? function returns TRUE if an error object is returned.

You can expand on the example to print more details about the error:


    if error? err: try [
        data: read %file.txt
    ][
        print ["Error:" mold disarm :err]
    ]

Now you will see the error details. Note that the DISARM function converts the error object (held in err) into a normal object.

For this code to work properly, the TRY block must return a value. Above, the block returns the file data which is fine, but if you use something like a PRINT, you'll need to add another value to be returned from the block:


    if error? err: try [
        data: read %file.txt
        print data
        true
    ][
        print ["Error:" mold disarm :err]
    ]

Here TRUE is returned from the TRY so that a value gets assigned to the err variable when the block does not encounter an error. You will need to remember this.

The ATTEMPT function provides another way to handle errors. It puts a wrapper around TRY for simple cases. ATTEMPT returns the value of the block if it succeeds, or a NONE if there is an error. For example:


    data: attempt [read %file.txt]
    if not data [
        print "Error reading file.txt"
    ]

The ATTEMPT function is more useful in cases like this:


    data: any [attempt [read %file.txt] "text"]

The code attempts to read the file, but if it cannot, the text string is used instead.

Here is another example:


    num-str: "1234"
    number: any [attempt [to-integer num-str] 0]
    print number
    1234

2006 REBOL Technologies REBOL.com REBOL.net