Skip to content

Throw

Status: Stable

documented, exercised by the test suite and/or worked examples, with no known limitations recorded.

Description

Throw[value]
    Stops evaluation and returns value to the nearest enclosing
    Catch. Throw[value, tag] is caught only by Catch[expr, form] whose form
    matches tag. Throw[value, tag, f] returns f[value, tag] if uncaught.

Examples

All examples below are verified against the current Mathilda build.

In[1]:= Catch[a; b; Throw[c]; d; e]
Out[1]= c

In[2]:= f[x_] := If[x > 10, Throw[overflow], x!]; Catch[f[2] + f[11]]
Out[2]= overflow

In[3]:= Catch[Do[If[i! > 10^10, Throw[i]], {i, 100}]]
Out[3]= 14

In[4]:= Catch[Throw[a, u], u]
Out[4]= a

In[5]:= Catch[Throw[v, tg], tg, {#1, #2} &]
Out[5]= {v, tg}

Implementation notes

  • Throw is Protected; Catch is HoldFirst, Protected (it drives evaluation of its body itself, so it can intercept a throw; form and f evaluate normally).
  • Implemented by sentinel propagation through the evaluator's normal return paths (no setjmp/longjmp), so every frame runs its own cleanup — leak-free.
  • The first Throw evaluated wins; a tagless Throw[value] is not caught by a form-Catch.
  • An uncaught Throw[value]/Throw[value, tag] returns Hold[Throw[...]] with a Throw::nocatch message; an uncaught Throw[value, tag, f] returns f[value, tag].

Attributes: Protected.

Implementation status

Stable — documented, exercised by the test suite and/or worked examples, with no known limitations recorded.

References