The 'catch' and 'throw' special forms allow for non-local exits and traps without going through the intermediate evaluations and function returns:
(catch tag-symbol [expr ...] (throw tag-symbol [expr]))
If there is a 'catch' for a '
> (catch 'mytag (+ 1 (+ 2 3))) 6
If there is no 'expr',
> (catch 'mytag) NIL
The 'expr' in 'throw' specifies what value is to be returned by the corresponding 'catch':
> (catch 'mytag (+ 1 (throw 'mytag 55))) 55
If there is no 'expr' in 'throw', NIL is returned to the corresponding 'catch':
> (catch 'mytag (throw 'mytag)) NIL
If more than one 'catch' is set up for the same
'
> (catch 'mytag (catch 'mytag (throw 'mytag)) (print 'hello)) HELLO
If a 'throw' is evaluated with no corresponding 'catch', an error is signalled:
> (catch 'mytag (throw 'foo)) error: no target for THROW
(defun in (x) (if (numberp x) ; if X is a number (+ x x) ; then double X (throw 'math 42))) ; else throw 42 (defun out (x) (princ "<") (princ (* (in x) 2)) ; double via multiply (princ ">") "there") (defun main (x) (catch 'math (out x))) ; catch the throw from IN > (in 5) 10 ; return value > (out 5) <20> ; screen output of PRINC "there" ; return value > (main 5) <20> ; screen output of PRINC "there" ; return value > (main 'a) < ; screen output of PRINC 42 ; return value
See
Note: 'catch' and 'throw' accept not only symbols as
'
> (catch "mytag" (throw "mytag")) error: no target for THROW
This was reproduced with
See also: