Catch

Catch[expr]

returns the argument of the first Throw generated in the evaluation of expr.

Catch[expr,form]

returns value from the first Throw[value,tag] for which form matches tag.

Catch[expr,form,f]

returns f[value,tag].

Details

  • Catch[expr,] always returns the value of expr if no Throw was generated during the evaluation.
  • form can be any expression, and is often a pattern.
  • tag in Throw[value,tag] is reevaluated every time it is compared to form.

Examples

open allclose all

Basic Examples  (3)

Exit to the enclosing Catch as soon as the Throw is evaluated:

Define a function that can "throw an exception":

The result of the Catch is just what is thrown by Throw:

Use Throw to exit a loop when a criterion is satisfied:

Scope  (5)

Catch can catch a Throw from inside essentially any function:

The nearest enclosing Catch catches the Throw:

Catch picks up the first Throw that is evaluated:

Throw need not occur lexically inside Catch:

A function that can throw a number of different exceptions:

A handler for the possible exceptions:

Generalizations & Extensions  (3)

Catch the Throw with tag u:

The inner Catch catches the Throw:

The outer Catch catches the Throw:

Keep the tag local:

Applications  (3)

Find the next prime after 1010:

Find the first power of 17 equal to 1 mod 19:

Stop if an iteration gets too large:

Properties & Relations  (1)

Use Check to throw an exception if a message is generated:

Introduced in 1988
 (1.0)
 |
Updated in 1996
 (3.0)