Skip to content

Catch ​

Evaluates an expression, recovering the value of any Throw inside it.

✓ checked against that system · ! checked, with disagreements (hover a chip)Wolfram LanguageCatch✓
Catch(expr)exprexpr's value, or (if a Throw happened while evaluating it) the value that ThrowThrow carried.
Catch(expr, tag)Like Catch(expr)Catch(expr), but only catches a ThrowThrow whose tag matches tagtag exactly — any other ThrowThrow (untagged, or a different tag) propagates past this CatchCatch.
Typed signatures
TypePackageApplies
(any, any?) -> anycombinatoricsalways

Domain: Collections

Details
  • Only exact tag equality is matched, not Wolfram's fuller pattern-matching form.
  • An error that is not one of our own ThrowThrows is never caught here — it propagates as a normal error would.

Examples

Basic #

with no Throw inside, Catch just returns the value

live ↗
InCatch(1+2)\mathrm{Catch}(1+2)Out33

Catch(expr, tag) recovers a Throw with a matching tag

live ↗
InCatch(Throw(ok,done),done)\mathrm{Catch}(\mathrm{Throw}(\mathrm{ok}, \mathrm{done}), \mathrm{done})Outok\mathrm{ok}
live ↗
InCatch(Do(If(k!>1010,Throw(k)),[k,100]))\mathrm{Catch}(\mathrm{Do}(\mathrm{If}(k!\gt10^{10}, \mathrm{Throw}(k)), \bigl\lbrack k, 100\bigr\rbrack))Out1414
Scope #

Throw exits the enclosing Catch, discarding the rest

live ↗
InCatch([a,Throw(b),c])\mathrm{Catch}(\bigl\lbrack a, \mathrm{Throw}(b), c\bigr\rbrack)Outbb

Only the first throw is reached

live ↗
InCatch([Throw(a),Throw(b),Throw(c)])\mathrm{Catch}(\bigl\lbrack\mathrm{Throw}(a), \mathrm{Throw}(b), \mathrm{Throw}(c)\bigr\rbrack)Outaa

A tag restricts which Catch receives the throw

live ↗
InCatch(Throw(a,u),u)\mathrm{Catch}(\mathrm{Throw}(a, u), u)Outaa

The inner Catch handles the throw, the outer list continues

live ↗
InCatch([Catch([a,Throw(b),c]),d,k])\mathrm{Catch}(\bigl\lbrack\mathrm{Catch}(\bigl\lbrack a, \mathrm{Throw}(b), c\bigr\rbrack), d, k\bigr\rbrack)Out[b,d,k]\bigl\lbrack b, d, k\bigr\rbrack
Applications #
live ↗
InCatch(Do(If(IsPrime(k),Throw(k)),[k,1010,1010+1 000]))\mathrm{Catch}(\mathrm{Do}(\mathrm{If}(\mathrm{IsPrime}(k), \mathrm{Throw}(k)), \bigl\lbrack k, 10^{10}, 10^{10}+1\,000\bigr\rbrack))Out10 000 000 01910\,000\,000\,019
live ↗
InCatch(Do(If(17k mod 19=1,Throw(k)),[k,19]))\mathrm{Catch}(\mathrm{Do}(\mathrm{If}(17^{k}\bmod19=1, \mathrm{Throw}(k)), \bigl\lbrack k, 19\bigr\rbrack))Out99
live ↗
InCatch(NestList(_1⁡↦if _1⁡>1 000 then Throw(_1⁡) else _1⁡2+1,2,6))\mathrm{Catch}(\mathrm{NestList}(\operatorname{\_1}↦\text{if }\operatorname{\_1}\gt1\,000\text{ then }\mathrm{Throw}(\operatorname{\_1})\text{ else }\operatorname{\_1}^2+1, 2, 6))Out458 330458\,330
About
Examples10
Checked againstWolfram Language 10 agree
CrosswalkWolfram Language

See also: Throw