REBOL 3 Docs Guide Concepts Functions Datatypes Errors
  TOC < Back Next >   Updated: 17-Aug-2010 Edit History  

REBOL 3 Functions: try

try  block  /except  code

Tries to DO a block and returns its value or an error.

Arguments:

block [block!]

Refinements:

/except - On exception, evaluate this code block

code [block! any-function!]

See also:

attempt   error?   do  

Description

The try function evaluates a block and will capture any errors that occur during that evaluation.

The purpose of try is to give your own code the opportunity to handle errors, rather than causing your program to terminate with an error message.

For example, in this line:

try [delete %afile.txt]

if the file does not exist, then the error will not cause your program to terminate.

Return Value

The try function returns an error value if an error happened, otherwise it returns the normal result of the block.

Taking the above example, we can do something special if an error happened:

if error? try [delete %afile.txt] [print "delete failed"]

or, even use the error value itself:

if error? err: try [delete %afile.txt] [print ["delete failed:" mold err]]

Sometimes you'll want to use the value that was returned:

either error? val: try [1 + "x"] [print "nope"] [print val]
nope
either error? val: try [1 + 2] [print "nope"] [print val]
3

Exception Handling

The try function is for error handling, but there are times when you may be returning error objects as values, and you cannot distinguish between an error occurring and the error value itself. This is case rare, but it does happen.

For this situation the /except refinement is provided. If an error occurs, it will evaluate a exception handling function (or just a block). This indicates that an error exception happened (not just an error value being passed.)

The example below will catch the [bad-link:errors/zero-divide.txt] error within a function. The error is passed as the argument to the exception function, and a value (zero in this case) is returned from the try function:

try/except [1 / 0] func [value] [?? value 0]
value: make error! [
    code: 400
    type: 'Math
    id: 'zero-divide
    arg1: none
    arg2: none
    arg3: none
    near: [/ 0]
    where: [/ try]
 ]
 0

Shortcut

The attempt function is shortcut for the common pattern where you don't care about the specific error, and mainly just want the non-error result.

data: attempt [load %data.r]

The data will be either the data or none, if it failed to load.


  TOC < Back Next > REBOL.com - WIP Wiki Feedback Admin