Author: Carl Sassenrath
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:
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:
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:
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:
The ATTEMPT function is more useful in cases like this:
The code attempts to read the file, but if it cannot, the text string is used instead.
Here is another example: