An expression's evaluation may return an error—for example, when trying to divide a number by zero, or when a network call fails. Typically, an expression returning an error will result in failing the journey in the context in which it is executed. Try-expressions allow recovering from errors in expressions, possibly providing an alternate value for the result.
The syntax for a try-expression is as follows:
try body catch alternatewhere body is the expression to evaluate and guard from errors, and alternate is the alternate value to return in case of an error. If the evaluation of body completes successfully, its return will be the return value of the try-expression. Otherwise, the returned value will be the result of evaluating alternate.
Consider these examples. For try 3/2 catch 10, the guarded expression here (3/2) doesn't yield any error on evaluation so the try-expression returns its result (1.5). However, for try 3/0 catch 10, the guarded expression results in an error (division by zero), so the value of the alternate expression (10) will be returned.
If the alternate expression is a lambda, the try-expression behavior changes slightly. Instead of returning the alternate itself (which would be of a lambda type), the alternate will be invoked with a single parameter which is a description of the error that occurred; it is the return value of this invocation that will be returned from the try-expression.
Consider this example: try 3/0 catch (error)=>"Encountered an error: " + error. The return value would be the result of invoking the lambda (error)=>"Encountered an error: " + error with the error description as its single argument. So the overall return from this try-expression will be the string "Encountered an error: TSError: expression.arithmetic_error:[Division by zero]".