8.19 Catch and Throw

  1. catch Expr

Returns the value of Expr unless an exception occurs during the evaluation. In that case, the exception is caught.

For exceptions of class error, that is, run-time errors, {'EXIT',{Reason,Stack}} is returned.

For exceptions of class exit, that is, the code called exit(Term), {'EXIT',Term} is returned.

For exceptions of class throw, that is the code called throw(Term), Term is returned.

Reason depends on the type of error that occurred, and Stack is the stack of recent function calls, see Exit Reasons.

Examples:

  1. 1> catch 1+2.
  2. 3
  3. 2> catch 1+a.
  4. {'EXIT',{badarith,[...]}}

Notice that catch has low precedence and catch subexpressions often needs to be enclosed in a block expression or in parentheses:

  1. 3> A = catch 1+2.
  2. ** 1: syntax error before: 'catch' **
  3. 4> A = (catch 1+2).
  4. 3

The BIF throw(Any) can be used for non-local return from a function. It must be evaluated within a catch, which returns the value Any.

Example:

  1. 5> catch throw(hello).
  2. hello

If throw/1 is not evaluated within a catch, a nocatch run-time error occurs.