2 @c This is part of the GNU Guile Reference Manual.
3 @c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004
4 @c Free Software Foundation, Inc.
5 @c See the file guile.texi for copying conditions.
8 @node Control Mechanisms
9 @section Controlling the Flow of Program Execution
11 See @ref{Control Flow} for a discussion of how the more general control
12 flow of Scheme affects C code.
15 * begin:: Evaluating a sequence of expressions.
16 * if cond case:: Simple conditional evaluation.
17 * and or:: Conditional evaluation of a sequence.
18 * while do:: Iteration mechanisms.
19 * Continuations:: Continuations.
20 * Multiple Values:: Returning and accepting multiple values.
21 * Exceptions:: Throwing and catching exceptions.
22 * Error Reporting:: Procedures for signaling errors.
23 * Dynamic Wind:: Dealing with non-local entrance/exit.
24 * Handling Errors:: How to handle errors in C code.
28 @subsection Evaluating a Sequence of Expressions
32 @cindex expression sequencing
34 The @code{begin} syntax is used for grouping several expressions
35 together so that they are treated as if they were one expression.
36 This is particularly important when syntactic expressions are used
37 which only allow one expression, but the programmer wants to use more
38 than one expression in that place. As an example, consider the
39 conditional expression below:
43 (begin (display "greater") (newline)))
46 If the two calls to @code{display} and @code{newline} were not embedded
47 in a @code{begin}-statement, the call to @code{newline} would get
48 misinterpreted as the else-branch of the @code{if}-expression.
50 @deffn syntax begin expr1 expr2 @dots{}
51 The expression(s) are evaluated in left-to-right order and the value
52 of the last expression is returned as the value of the
53 @code{begin}-expression. This expression type is used when the
54 expressions before the last one are evaluated for their side effects.
56 Guile also allows the expression @code{(begin)}, a @code{begin} with no
57 sub-expressions. Such an expression returns the `unspecified' value.
61 @subsection Simple Conditional Evaluation
63 @cindex conditional evaluation
68 Guile provides three syntactic constructs for conditional evaluation.
69 @code{if} is the normal if-then-else expression (with an optional else
70 branch), @code{cond} is a conditional expression with multiple branches
71 and @code{case} branches if an expression has one of a set of constant
74 @deffn syntax if test consequent [alternate]
75 All arguments may be arbitrary expressions. First, @var{test} is
76 evaluated. If it returns a true value, the expression @var{consequent}
77 is evaluated and @var{alternate} is ignored. If @var{test} evaluates to
78 @code{#f}, @var{alternate} is evaluated instead. The value of the
79 evaluated branch (@var{consequent} or @var{alternate}) is returned as
80 the value of the @code{if} expression.
82 When @var{alternate} is omitted and the @var{test} evaluates to
83 @code{#f}, the value of the expression is not specified.
86 @deffn syntax cond clause1 clause2 @dots{}
87 Each @code{cond}-clause must look like this:
90 (@var{test} @var{expression} @dots{})
93 where @var{test} and @var{expression} are arbitrary expression, or like
97 (@var{test} => @var{expression})
100 where @var{expression} must evaluate to a procedure.
102 The @var{test}s of the clauses are evaluated in order and as soon as one
103 of them evaluates to a true values, the corresponding @var{expression}s
104 are evaluated in order and the last value is returned as the value of
105 the @code{cond}-expression. For the @code{=>} clause type,
106 @var{expression} is evaluated and the resulting procedure is applied to
107 the value of @var{test}. The result of this procedure application is
108 then the result of the @code{cond}-expression.
111 @cindex general cond clause
112 @cindex multiple values and cond
113 One additional @code{cond}-clause is available as an extension to
117 (@var{test} @var{guard} => @var{expression})
120 where @var{guard} and @var{expression} must evaluate to procedures.
121 For this clause type, @var{test} may return multiple values, and
122 @code{cond} ignores its boolean state; instead, @code{cond} evaluates
123 @var{guard} and applies the resulting procedure to the value(s) of
124 @var{test}, as if @var{guard} were the @var{consumer} argument of
125 @code{call-with-values}. Iff the result of that procedure call is a
126 true value, it evaluates @var{expression} and applies the resulting
127 procedure to the value(s) of @var{test}, in the same manner as the
128 @var{guard} was called.
130 The @var{test} of the last @var{clause} may be the symbol @code{else}.
131 Then, if none of the preceding @var{test}s is true, the
132 @var{expression}s following the @code{else} are evaluated to produce the
133 result of the @code{cond}-expression.
136 @deffn syntax case key clause1 clause2 @dots{}
137 @var{key} may be any expression, the @var{clause}s must have the form
140 ((@var{datum1} @dots{}) @var{expr1} @var{expr2} @dots{})
143 and the last @var{clause} may have the form
146 (else @var{expr1} @var{expr2} @dots{})
149 All @var{datum}s must be distinct. First, @var{key} is evaluated. The
150 the result of this evaluation is compared against all @var{datum}s using
151 @code{eqv?}. When this comparison succeeds, the expression(s) following
152 the @var{datum} are evaluated from left to right, returning the value of
153 the last expression as the result of the @code{case} expression.
155 If the @var{key} matches no @var{datum} and there is an
156 @code{else}-clause, the expressions following the @code{else} are
157 evaluated. If there is no such clause, the result of the expression is
163 @subsection Conditional Evaluation of a Sequence of Expressions
165 @code{and} and @code{or} evaluate all their arguments in order, similar
166 to @code{begin}, but evaluation stops as soon as one of the expressions
167 evaluates to false or true, respectively.
169 @deffn syntax and expr @dots{}
170 Evaluate the @var{expr}s from left to right and stop evaluation as soon
171 as one expression evaluates to @code{#f}; the remaining expressions are
172 not evaluated. The value of the last evaluated expression is returned.
173 If no expression evaluates to @code{#f}, the value of the last
174 expression is returned.
176 If used without expressions, @code{#t} is returned.
179 @deffn syntax or expr @dots{}
180 Evaluate the @var{expr}s from left to right and stop evaluation as soon
181 as one expression evaluates to a true value (that is, a value different
182 from @code{#f}); the remaining expressions are not evaluated. The value
183 of the last evaluated expression is returned. If all expressions
184 evaluate to @code{#f}, @code{#f} is returned.
186 If used without expressions, @code{#f} is returned.
191 @subsection Iteration mechanisms
197 Scheme has only few iteration mechanisms, mainly because iteration in
198 Scheme programs is normally expressed using recursion. Nevertheless,
199 R5RS defines a construct for programming loops, calling @code{do}. In
200 addition, Guile has an explicit looping syntax called @code{while}.
202 @deffn syntax do ((variable init [step]) @dots{}) (test [expr @dots{}]) body @dots{}
203 Bind @var{variable}s and evaluate @var{body} until @var{test} is true.
204 The return value is the last @var{expr} after @var{test}, if given. A
205 simple example will illustrate the basic form,
215 Or with two variables and a final return value,
222 (format #t "3**~s is ~s\n" i p))
232 The @var{variable} bindings are established like a @code{let}, in that
233 the expressions are all evaluated and then all bindings made. When
234 iterating, the optional @var{step} expressions are evaluated with the
235 previous bindings in scope, then new bindings all made.
237 The @var{test} expression is a termination condition. Looping stops
238 when the @var{test} is true. It's evaluated before running the
239 @var{body} each time, so if it's true the first time then @var{body}
242 The optional @var{expr}s after the @var{test} are evaluated at the end
243 of looping, with the final @var{variable} bindings available. The
244 last @var{expr} gives the return value, or if there are no @var{expr}s
245 the return value is unspecified.
247 Each iteration establishes bindings to fresh locations for the
248 @var{variable}s, like a new @code{let} for each iteration. This is
249 done for @var{variable}s without @var{step} expressions too. The
250 following illustrates this, showing how a new @code{i} is captured by
251 the @code{lambda} in each iteration (@pxref{About Closure,, The
252 Concept of Closure}).
258 (set! lst (cons (lambda () i) lst)))
259 (map (lambda (proc) (proc)) lst)
265 @deffn syntax while cond body @dots{}
266 Run a loop executing the @var{body} forms while @var{cond} is true.
267 @var{cond} is tested at the start of each iteration, so if it's
268 @code{#f} the first time then @var{body} is not executed at all. The
269 return value is unspecified.
271 Within @code{while}, two extra bindings are provided, they can be used
272 from both @var{cond} and @var{body}.
274 @deffn {Scheme Procedure} break
275 Break out of the @code{while} form.
278 @deffn {Scheme Procedure} continue
279 Abandon the current iteration, go back to the start and test
280 @var{cond} again, etc.
283 Each @code{while} form gets its own @code{break} and @code{continue}
284 procedures, operating on that @code{while}. This means when loops are
285 nested the outer @code{break} can be used to escape all the way out.
290 (let ((outer-break break))
297 Note that each @code{break} and @code{continue} procedure can only be
298 used within the dynamic extent of its @code{while}. Outside the
299 @code{while} their behaviour is unspecified.
303 Another very common way of expressing iteration in Scheme programs is
304 the use of the so-called @dfn{named let}.
306 Named let is a variant of @code{let} which creates a procedure and calls
307 it in one step. Because of the newly created procedure, named let is
308 more powerful than @code{do}--it can be used for iteration, but also
309 for arbitrary recursion.
311 @deffn syntax let variable bindings body
312 For the definition of @var{bindings} see the documentation about
313 @code{let} (@pxref{Local Bindings}).
315 Named @code{let} works as follows:
319 A new procedure which accepts as many arguments as are in @var{bindings}
320 is created and bound locally (using @code{let}) to @var{variable}. The
321 new procedure's formal argument names are the name of the
325 The @var{body} expressions are inserted into the newly created procedure.
328 The procedure is called with the @var{init} expressions as the formal
332 The next example implements a loop which iterates (by recursion) 1000
347 @subsection Continuations
348 @cindex continuations
350 A ``continuation'' is the code that will execute when a given function
351 or expression returns. For example, consider
356 (display (bar)) (newline)
360 The continuation from the call to @code{bar} comprises a
361 @code{display} of the value returned, a @code{newline} and an
362 @code{exit}. This can be expressed as a function of one argument.
366 (display r) (newline)
370 In Scheme, continuations are represented as special procedures just
371 like this. The special property is that when a continuation is called
372 it abandons the current program location and jumps directly to that
373 represented by the continuation.
375 A continuation is like a dynamic label, capturing at run-time a point
376 in program execution, including all the nested calls that have lead to
377 it (or rather the code that will execute when those calls return).
379 Continuations are created with the following functions.
381 @deffn {Scheme Procedure} call-with-current-continuation proc
382 @deffnx {Scheme Procedure} call/cc proc
383 @rnindex call-with-current-continuation
384 Capture the current continuation and call @code{(@var{proc}
385 @var{cont})} with it. The return value is the value returned by
386 @var{proc}, or when @code{(@var{cont} @var{value})} is later invoked,
387 the return is the @var{value} passed.
389 Normally @var{cont} should be called with one argument, but when the
390 location resumed is expecting multiple values (@pxref{Multiple
391 Values}) then they should be passed as multiple arguments, for
392 instance @code{(@var{cont} @var{x} @var{y} @var{z})}.
394 @var{cont} may only be used from the same side of a continuation
395 barrier as it was created (@pxref{Continuation Barriers}), and in a
396 multi-threaded program only from the thread in which it was created.
398 The call to @var{proc} is not part of the continuation captured, it runs
399 only when the continuation is created. Often a program will want to
400 store @var{cont} somewhere for later use; this can be done in
403 The @code{call} in the name @code{call-with-current-continuation}
404 refers to the way a call to @var{proc} gives the newly created
405 continuation. It's not related to the way a call is used later to
406 invoke that continuation.
408 @code{call/cc} is an alias for @code{call-with-current-continuation}.
409 This is in common use since the latter is rather long.
412 @deftypefn {C Function} SCM scm_make_continuation (int *first)
413 Capture the current continuation as described above. The return value
414 is the new continuation, and @var{*first} is set to 1.
416 When the continuation is invoked, @code{scm_make_continuation} will
417 return again, this time returning the value (or set of multiple
418 values) passed in that invocation, and with @var{*first} set to 0.
423 Here is a simple example,
427 (format #t "the return is ~a\n"
431 @result{} the return is 1
434 @result{} the return is 2
437 @code{call/cc} captures a continuation in which the value returned is
438 going to be displayed by @code{format}. The @code{lambda} stores this
439 in @code{kont} and gives an initial return @code{1} which is
440 displayed. The later invocation of @code{kont} resumes the captured
441 point, but this time returning @code{2}, which is displayed.
443 When Guile is run interactively, a call to @code{format} like this has
444 an implicit return back to the read-eval-print loop. @code{call/cc}
445 captures that like any other return, which is why interactively
446 @code{kont} will come back to read more input.
449 C programmers may note that @code{call/cc} is like @code{setjmp} in
450 the way it records at runtime a point in program execution. A call to
451 a continuation is like a @code{longjmp} in that it abandons the
452 present location and goes to the recorded one. Like @code{longjmp},
453 the value passed to the continuation is the value returned by
454 @code{call/cc} on resuming there. However @code{longjmp} can only go
455 up the program stack, but the continuation mechanism can go anywhere.
457 When a continuation is invoked, @code{call/cc} and subsequent code
458 effectively ``returns'' a second time. It can be confusing to imagine
459 a function returning more times than it was called. It may help
460 instead to think of it being stealthily re-entered and then program
461 flow going on as normal.
463 @code{dynamic-wind} (@pxref{Dynamic Wind}) can be used to ensure setup
464 and cleanup code is run when a program locus is resumed or abandoned
465 through the continuation mechanism.
468 Continuations are a powerful mechanism, and can be used to implement
469 almost any sort of control structure, such as loops, coroutines, or
472 However the implementation of continuations in Guile is not as
473 efficient as one might hope, because Guile is designed to cooperate
474 with programs written in other languages, such as C, which do not know
475 about continuations. Basically continuations are captured by a block
476 copy of the stack, and resumed by copying back.
478 For this reason, generally continuations should be used only when
479 there is no other simple way to achieve the desired result, or when
480 the elegance of the continuation mechanism outweighs the need for
483 Escapes upwards from loops or nested functions are generally best
484 handled with exceptions (@pxref{Exceptions}). Coroutines can be
485 efficiently implemented with cooperating threads (a thread holds a
486 full program stack but doesn't copy it around the way continuations
490 @node Multiple Values
491 @subsection Returning and Accepting Multiple Values
493 @cindex multiple values
496 Scheme allows a procedure to return more than one value to its caller.
497 This is quite different to other languages which only allow
498 single-value returns. Returning multiple values is different from
499 returning a list (or pair or vector) of values to the caller, because
500 conceptually not @emph{one} compound object is returned, but several
503 The primitive procedures for handling multiple values are @code{values}
504 and @code{call-with-values}. @code{values} is used for returning
505 multiple values from a procedure. This is done by placing a call to
506 @code{values} with zero or more arguments in tail position in a
507 procedure body. @code{call-with-values} combines a procedure returning
508 multiple values with a procedure which accepts these values as
512 @deffn {Scheme Procedure} values arg1 @dots{} argN
513 @deffnx {C Function} scm_values (args)
514 Delivers all of its arguments to its continuation. Except for
515 continuations created by the @code{call-with-values} procedure,
516 all continuations take exactly one value. The effect of
517 passing no value or more than one value to continuations that
518 were not created by @code{call-with-values} is unspecified.
520 For @code{scm_values}, @var{args} is a list of arguments and the
521 return is a multiple-values object which the caller can return. In
522 the current implementation that object shares structure with
523 @var{args}, so @var{args} should not be modified subsequently.
526 @rnindex call-with-values
527 @deffn {Scheme Procedure} call-with-values producer consumer
528 Calls its @var{producer} argument with no values and a
529 continuation that, when passed some values, calls the
530 @var{consumer} procedure with those values as arguments. The
531 continuation for the call to @var{consumer} is the continuation
532 of the call to @code{call-with-values}.
535 (call-with-values (lambda () (values 4 5))
541 (call-with-values * -)
546 In addition to the fundamental procedures described above, Guile has a
547 module which exports a syntax called @code{receive}, which is much more
548 convenient. If you want to use it in your programs, you have to load
549 the module @code{(ice-9 receive)} with the statement
552 (use-modules (ice-9 receive))
555 @deffn {library syntax} receive formals expr body @dots{}
556 Evaluate the expression @var{expr}, and bind the result values (zero or
557 more) to the formal arguments in the formal argument list @var{formals}.
558 @var{formals} must have the same syntax like the formal argument list
559 used in @code{lambda} (@pxref{Lambda}). After binding the variables,
560 the expressions in @var{body} @dots{} are evaluated in order.
565 @subsection Exceptions
566 @cindex error handling
567 @cindex exception handling
569 A common requirement in applications is to want to jump
570 @dfn{non-locally} from the depths of a computation back to, say, the
571 application's main processing loop. Usually, the place that is the
572 target of the jump is somewhere in the calling stack of procedures that
573 called the procedure that wants to jump back. For example, typical
574 logic for a key press driven application might look something like this:
578 read the next key press and call dispatch-key
581 lookup the key in a keymap and call an appropriate procedure,
585 interactively read the required file name, then call
589 check whether file exists; if not, jump back to main-loop
593 The jump back to @code{main-loop} could be achieved by returning through
594 the stack one procedure at a time, using the return value of each
595 procedure to indicate the error condition, but Guile (like most modern
596 programming languages) provides an additional mechanism called
597 @dfn{exception handling} that can be used to implement such jumps much
601 * Exception Terminology:: Different ways to say the same thing.
602 * Catch:: Setting up to catch exceptions.
603 * Throw Handlers:: Adding extra handling to a throw.
604 * Lazy Catch:: Catch without unwinding the stack.
605 * Throw:: Throwing an exception.
606 * Exception Implementation:: How Guile implements exceptions.
610 @node Exception Terminology
611 @subsubsection Exception Terminology
613 There are several variations on the terminology for dealing with
614 non-local jumps. It is useful to be aware of them, and to realize
615 that they all refer to the same basic mechanism.
619 Actually making a non-local jump may be called @dfn{raising an
620 exception}, @dfn{raising a signal}, @dfn{throwing an exception} or
621 @dfn{doing a long jump}. When the jump indicates an error condition,
622 people may talk about @dfn{signalling}, @dfn{raising} or @dfn{throwing}
626 Handling the jump at its target may be referred to as @dfn{catching} or
627 @dfn{handling} the @dfn{exception}, @dfn{signal} or, where an error
628 condition is involved, @dfn{error}.
631 Where @dfn{signal} and @dfn{signalling} are used, special care is needed
632 to avoid the risk of confusion with POSIX signals.
634 This manual prefers to speak of throwing and catching exceptions, since
635 this terminology matches the corresponding Guile primitives.
639 @subsubsection Catching Exceptions
641 @code{catch} is used to set up a target for a possible non-local jump.
642 The arguments of a @code{catch} expression are a @dfn{key}, which
643 restricts the set of exceptions to which this @code{catch} applies, a
644 thunk that specifies the code to execute and one or two @dfn{handler}
645 procedures that say what to do if an exception is thrown while executing
646 the code. If the execution thunk executes @dfn{normally}, which means
647 without throwing any exceptions, the handler procedures are not called
650 When an exception is thrown using the @code{throw} function, the first
651 argument of the @code{throw} is a symbol that indicates the type of the
652 exception. For example, Guile throws an exception using the symbol
653 @code{numerical-overflow} to indicate numerical overflow errors such as
659 ABORT: (numerical-overflow)
662 The @var{key} argument in a @code{catch} expression corresponds to this
663 symbol. @var{key} may be a specific symbol, such as
664 @code{numerical-overflow}, in which case the @code{catch} applies
665 specifically to exceptions of that type; or it may be @code{#t}, which
666 means that the @code{catch} applies to all exceptions, irrespective of
669 The second argument of a @code{catch} expression should be a thunk
670 (i.e. a procedure that accepts no arguments) that specifies the normal
671 case code. The @code{catch} is active for the execution of this thunk,
672 including any code called directly or indirectly by the thunk's body.
673 Evaluation of the @code{catch} expression activates the catch and then
676 The third argument of a @code{catch} expression is a handler procedure.
677 If an exception is thrown, this procedure is called with exactly the
678 arguments specified by the @code{throw}. Therefore, the handler
679 procedure must be designed to accept a number of arguments that
680 corresponds to the number of arguments in all @code{throw} expressions
681 that can be caught by this @code{catch}.
683 The fourth, optional argument of a @code{catch} expression is another
684 handler procedure, called the @dfn{pre-unwind} handler. It differs from
685 the third argument in that if an exception is thrown, it is called,
686 @emph{before} the third argument handler, in exactly the dynamic context
687 of the @code{throw} expression that threw the exception. This means
688 that it is useful for capturing or displaying the stack at the point of
689 the @code{throw}, or for examining other aspects of the dynamic context,
690 such as fluid values, before the context is unwound back to that of the
691 prevailing @code{catch}.
693 @deffn {Scheme Procedure} catch key thunk handler [pre-unwind-handler]
694 @deffnx {C Function} scm_catch_with_pre_unwind_handler (key, thunk, handler, pre_unwind_handler)
695 @deffnx {C Function} scm_catch (key, thunk, handler)
696 Invoke @var{thunk} in the dynamic context of @var{handler} for
697 exceptions matching @var{key}. If thunk throws to the symbol
698 @var{key}, then @var{handler} is invoked this way:
700 (handler key args ...)
703 @var{key} is a symbol or @code{#t}.
705 @var{thunk} takes no arguments. If @var{thunk} returns
706 normally, that is the return value of @code{catch}.
708 Handler is invoked outside the scope of its own @code{catch}.
709 If @var{handler} again throws to the same key, a new handler
710 from further up the call chain is invoked.
712 If the key is @code{#t}, then a throw to @emph{any} symbol will
713 match this call to @code{catch}.
715 If a @var{pre-unwind-handler} is given and @var{thunk} throws
716 an exception that matches @var{key}, Guile calls the
717 @var{pre-unwind-handler} before unwinding the dynamic state and
718 invoking the main @var{handler}. @var{pre-unwind-handler} should
719 be a procedure with the same signature as @var{handler}, that
720 is @code{(lambda (key . args))}. It is typically used to save
721 the stack at the point where the exception occurred, but can also
722 query other parts of the dynamic state at that point, such as
725 A @var{pre-unwind-handler} can exit either normally or non-locally.
726 If it exits normally, Guile unwinds the stack and dynamic context
727 and then calls the normal (third argument) handler. If it exits
728 non-locally, that exit determines the continuation.
731 If a handler procedure needs to match a variety of @code{throw}
732 expressions with varying numbers of arguments, you should write it like
741 The @var{key} argument is guaranteed always to be present, because a
742 @code{throw} without a @var{key} is not valid. The number and
743 interpretation of the @var{args} varies from one type of exception to
744 another, but should be specified by the documentation for each exception
747 Note that, once the normal (post-unwind) handler procedure is invoked,
748 the catch that led to the handler procedure being called is no longer
749 active. Therefore, if the handler procedure itself throws an exception,
750 that exception can only be caught by another active catch higher up the
751 call stack, if there is one.
754 @deftypefn {C Function} SCM scm_c_catch (SCM tag, scm_t_catch_body body, void *body_data, scm_t_catch_handler handler, void *handler_data, scm_t_catch_handler pre_unwind_handler, void *pre_unwind_handler_data)
755 @deftypefnx {C Function} SCM scm_internal_catch (SCM tag, scm_t_catch_body body, void *body_data, scm_t_catch_handler handler, void *handler_data)
756 The above @code{scm_catch_with_pre_unwind_handler} and @code{scm_catch}
757 take Scheme procedures as body and handler arguments.
758 @code{scm_c_catch} and @code{scm_internal_catch} are equivalents taking
761 @var{body} is called as @code{@var{body} (@var{body_data})} with a catch
762 on exceptions of the given @var{tag} type. If an exception is caught,
763 @var{pre_unwind_handler} and @var{handler} are called as
764 @code{@var{handler} (@var{handler_data}, @var{key}, @var{args})}.
765 @var{key} and @var{args} are the @code{SCM} key and argument list from
768 @tpindex scm_t_catch_body
769 @tpindex scm_t_catch_handler
770 @var{body} and @var{handler} should have the following prototypes.
771 @code{scm_t_catch_body} and @code{scm_t_catch_handler} are pointer
775 SCM body (void *data);
776 SCM handler (void *data, SCM key, SCM args);
779 The @var{body_data} and @var{handler_data} parameters are passed to
780 the respective calls so an application can communicate extra
781 information to those functions.
783 If the data consists of an @code{SCM} object, care should be taken
784 that it isn't garbage collected while still required. If the
785 @code{SCM} is a local C variable, one way to protect it is to pass a
786 pointer to that variable as the data parameter, since the C compiler
787 will then know the value must be held on the stack. Another way is to
788 use @code{scm_remember_upto_here_1} (@pxref{Remembering During
794 @subsubsection Throw Handlers
796 It's sometimes useful to be able to intercept an exception that is being
797 thrown, but without changing where in the dynamic context that exception
798 will eventually be caught. This could be to clean up some related state
799 or to pass information about the exception to a debugger, for example.
800 The @code{with-throw-handler} procedure provides a way to do this.
802 @deffn {Scheme Procedure} with-throw-handler key thunk handler
803 @deffnx {C Function} scm_with_throw_handler (key, thunk, handler)
804 Add @var{handler} to the dynamic context as a throw handler
805 for key @var{key}, then invoke @var{thunk}.
808 @deftypefn {C Function} SCM scm_c_with_throw_handler (SCM tag, scm_t_catch_body body, void *body_data, scm_t_catch_handler handler, void *handler_data, int lazy_catch_p)
809 The above @code{scm_with_throw_handler} takes Scheme procedures as body
810 (thunk) and handler arguments. @code{scm_c_with_throw_handler} is an
811 equivalent taking C functions. See @code{scm_c_catch} (@pxref{Catch})
812 for a description of the parameters, the behaviour however of course
813 follows @code{with-throw-handler}.
816 If @var{thunk} throws an exception, Guile handles that exception by
817 invoking the innermost @code{catch} or throw handler whose key matches
818 that of the exception. When the innermost thing is a throw handler,
819 Guile calls the specified handler procedure using @code{(apply
820 @var{handler} key args)}. The handler procedure may either return
821 normally or exit non-locally. If it returns normally, Guile passes the
822 exception on to the next innermost @code{catch} or throw handler. If it
823 exits non-locally, that exit determines the continuation.
825 The behaviour of a throw handler is very similar to that of a
826 @code{catch} expression's optional pre-unwind handler. In particular, a
827 throw handler's handler procedure is invoked in the exact dynamic
828 context of the @code{throw} expression, just as a pre-unwind handler is.
829 @code{with-throw-handler} may be seen as a half-@code{catch}: it does
830 everything that a @code{catch} would do until the point where
831 @code{catch} would start unwinding the stack and dynamic context, but
832 then it rethrows to the next innermost @code{catch} or throw handler
837 @subsubsection Catch Without Unwinding
839 Before version 1.8, Guile's closest equivalent to
840 @code{with-throw-handler} was @code{lazy-catch}. From version 1.8
841 onwards we recommend using @code{with-throw-handler} because its
842 behaviour is more useful than that of @code{lazy-catch}, but
843 @code{lazy-catch} is still supported as well.
845 A @dfn{lazy catch} is used in the same way as a normal @code{catch},
846 with @var{key}, @var{thunk} and @var{handler} arguments specifying the
847 exception type, normal case code and handler procedure, but differs in
848 one important respect: the handler procedure is executed without
849 unwinding the call stack from the context of the @code{throw} expression
850 that caused the handler to be invoked.
852 @deffn {Scheme Procedure} lazy-catch key thunk handler
853 @deffnx {C Function} scm_lazy_catch (key, thunk, handler)
854 This behaves exactly like @code{catch}, except that it does
855 not unwind the stack before invoking @var{handler}.
856 If the @var{handler} procedure returns normally, Guile
857 rethrows the same exception again to the next innermost catch,
858 lazy-catch or throw handler. If the @var{handler} exits
859 non-locally, that exit determines the continuation.
862 @deftypefn {C Function} SCM scm_internal_lazy_catch (SCM tag, scm_t_catch_body body, void *body_data, scm_t_catch_handler handler, void *handler_data)
863 The above @code{scm_lazy_catch} takes Scheme procedures as body and
864 handler arguments. @code{scm_internal_lazy_catch} is an equivalent
865 taking C functions. See @code{scm_internal_catch} (@pxref{Catch}) for
866 a description of the parameters, the behaviour however of course
867 follows @code{lazy-catch}.
870 Typically @var{handler} is used to display a backtrace of the stack at
871 the point where the corresponding @code{throw} occurred, or to save off
872 this information for possible display later.
874 Not unwinding the stack means that throwing an exception that is caught
875 by a @code{lazy-catch} is @emph{almost} equivalent to calling the
876 @code{lazy-catch}'s handler inline instead of each @code{throw}, and
877 then omitting the surrounding @code{lazy-catch}. In other words,
881 (lambda () @dots{} (throw 'key args @dots{}) @dots{})
886 is @emph{almost} equivalent to
889 ((lambda () @dots{} (handler 'key args @dots{}) @dots{}))
893 But why only @emph{almost}? The difference is that with
894 @code{lazy-catch} (as with normal @code{catch}), the dynamic context is
895 unwound back to just outside the @code{lazy-catch} expression before
896 invoking the handler. (For an introduction to what is meant by dynamic
897 context, @xref{Dynamic Wind}.)
899 Then, when the handler @emph{itself} throws an exception, that exception
900 must be caught by some kind of @code{catch} (including perhaps another
901 @code{lazy-catch}) higher up the call stack.
903 The dynamic context also includes @code{with-fluids} blocks
904 (@pxref{Fluids and Dynamic States}),
905 so the effect of unwinding the dynamic context can also be seen in fluid
906 variable values. This is illustrated by the following code, in which
907 the normal case thunk uses @code{with-fluids} to temporarily change the
911 (define f (make-fluid))
912 (fluid-set! f "top level value")
914 (define (handler . args)
915 (cons (fluid-ref f) args))
919 (with-fluids ((f "local value"))
923 ("top level value" foo)
926 (with-fluids ((f "local value"))
933 In the @code{lazy-catch} version, the unwinding of dynamic context
934 restores @code{f} to its value outside the @code{with-fluids} block
935 before the handler is invoked, so the handler's @code{(fluid-ref f)}
936 returns the external value.
938 @code{lazy-catch} is useful because it permits the implementation of
939 debuggers and other reflective programming tools that need to access the
940 state of the call stack at the exact point where an exception or an
941 error is thrown. For an example of this, see REFFIXME:stack-catch.
943 It should be obvious from the above that @code{lazy-catch} is very
944 similar to @code{with-throw-handler}. In fact Guile implements
945 @code{lazy-catch} in exactly the same way as @code{with-throw-handler},
946 except with a flag set to say ``where there are slight differences
947 between what @code{with-throw-handler} and @code{lazy-catch} would do,
948 do what @code{lazy-catch} has always done''. There are two such
953 @code{with-throw-handler} handlers execute in the full dynamic context
954 of the originating @code{throw} call. @code{lazy-catch} handlers
955 execute in the dynamic context of the @code{lazy-catch} expression,
956 excepting only that the stack has not yet been unwound from the point of
957 the @code{throw} call.
960 If a @code{with-throw-handler} handler throws to a key that does not
961 match the @code{with-throw-handler} expression's @var{key}, the new
962 throw may be handled by a @code{catch} or throw handler that is _closer_
963 to the throw than the first @code{with-throw-handler}. If a
964 @code{lazy-catch} handler throws, it will always be handled by a
965 @code{catch} or throw handler that is higher up the dynamic context than
966 the first @code{lazy-catch}.
969 Here is an example to illustrate the second difference:
974 (with-throw-handler 'b
986 This code will call @code{inner-handler} and then continue with the
987 continuation of the inner @code{catch}. If the
988 @code{with-throw-handler} was changed to @code{lazy-catch}, however, the
989 code would call @code{outer-handler} and then continue with the
990 continuation of the outer @code{catch}.
992 Modulo these two differences, any statements in the previous and
993 following subsections about throw handlers apply to lazy catches as
998 @subsubsection Throwing Exceptions
1000 The @code{throw} primitive is used to throw an exception. One argument,
1001 the @var{key}, is mandatory, and must be a symbol; it indicates the type
1002 of exception that is being thrown. Following the @var{key},
1003 @code{throw} accepts any number of additional arguments, whose meaning
1004 depends on the exception type. The documentation for each possible type
1005 of exception should specify the additional arguments that are expected
1006 for that kind of exception.
1008 @deffn {Scheme Procedure} throw key . args
1009 @deffnx {C Function} scm_throw (key, args)
1010 Invoke the catch form matching @var{key}, passing @var{args} to the
1013 @var{key} is a symbol. It will match catches of the same symbol or of
1016 If there is no handler at all, Guile prints an error and then exits.
1019 When an exception is thrown, it will be caught by the innermost
1020 @code{catch} or throw handler that applies to the type of the thrown
1021 exception; in other words, whose @var{key} is either @code{#t} or the
1022 same symbol as that used in the @code{throw} expression. Once Guile has
1023 identified the appropriate @code{catch} or throw handler, it handles the
1024 exception by applying the relevant handler procedure(s) to the arguments
1025 of the @code{throw}.
1027 If there is no appropriate @code{catch} or throw handler for a thrown
1028 exception, Guile prints an error to the current error port indicating an
1029 uncaught exception, and then exits. In practice, it is quite difficult
1030 to observe this behaviour, because Guile when used interactively
1031 installs a top level @code{catch} handler that will catch all exceptions
1032 and print an appropriate error message @emph{without} exiting. For
1033 example, this is what happens if you try to throw an unhandled exception
1034 in the standard Guile REPL; note that Guile's command loop continues
1035 after the error message:
1038 guile> (throw 'badex)
1039 <unnamed port>:3:1: In procedure gsubr-apply @dots{}
1040 <unnamed port>:3:1: unhandled-exception: badex
1045 The default uncaught exception behaviour can be observed by evaluating a
1046 @code{throw} expression from the shell command line:
1049 $ guile -c "(begin (throw 'badex) (display \"here\\n\"))"
1050 guile: uncaught throw to badex: ()
1055 That Guile exits immediately following the uncaught exception
1056 is shown by the absence of any output from the @code{display}
1057 expression, because Guile never gets to the point of evaluating that
1061 @node Exception Implementation
1062 @subsubsection How Guile Implements Exceptions
1064 It is traditional in Scheme to implement exception systems using
1065 @code{call-with-current-continuation}. Continuations
1066 (@pxref{Continuations}) are such a powerful concept that any other
1067 control mechanism --- including @code{catch} and @code{throw} --- can be
1068 implemented in terms of them.
1070 Guile does not implement @code{catch} and @code{throw} like this,
1071 though. Why not? Because Guile is specifically designed to be easy to
1072 integrate with applications written in C. In a mixed Scheme/C
1073 environment, the concept of @dfn{continuation} must logically include
1074 ``what happens next'' in the C parts of the application as well as the
1075 Scheme parts, and it turns out that the only reasonable way of
1076 implementing continuations like this is to save and restore the complete
1079 So Guile's implementation of @code{call-with-current-continuation} is a
1080 stack copying one. This allows it to interact well with ordinary C
1081 code, but means that creating and calling a continuation is slowed down
1082 by the time that it takes to copy the C stack.
1084 The more targeted mechanism provided by @code{catch} and @code{throw}
1085 does not need to save and restore the C stack because the @code{throw}
1086 always jumps to a location higher up the stack of the code that executes
1087 the @code{throw}. Therefore Guile implements the @code{catch} and
1088 @code{throw} primitives independently of
1089 @code{call-with-current-continuation}, in a way that takes advantage of
1090 this @emph{upwards only} nature of exceptions.
1093 @node Error Reporting
1094 @subsection Procedures for Signaling Errors
1096 Guile provides a set of convenience procedures for signaling error
1097 conditions that are implemented on top of the exception primitives just
1100 @deffn {Scheme Procedure} error msg args @dots{}
1101 Raise an error with key @code{misc-error} and a message constructed by
1102 displaying @var{msg} and writing @var{args}.
1105 @deffn {Scheme Procedure} scm-error key subr message args data
1106 @deffnx {C Function} scm_error_scm (key, subr, message, args, data)
1107 Raise an error with key @var{key}. @var{subr} can be a string
1108 naming the procedure associated with the error, or @code{#f}.
1109 @var{message} is the error message string, possibly containing
1110 @code{~S} and @code{~A} escapes. When an error is reported,
1111 these are replaced by formatting the corresponding members of
1112 @var{args}: @code{~A} (was @code{%s} in older versions of
1113 Guile) formats using @code{display} and @code{~S} (was
1114 @code{%S}) formats using @code{write}. @var{data} is a list or
1115 @code{#f} depending on @var{key}: if @var{key} is
1116 @code{system-error} then it should be a list containing the
1117 Unix @code{errno} value; If @var{key} is @code{signal} then it
1118 should be a list containing the Unix signal number; If
1119 @var{key} is @code{out-of-range} or @code{wrong-type-arg},
1120 it is a list containing the bad value; otherwise
1121 it will usually be @code{#f}.
1124 @deffn {Scheme Procedure} strerror err
1125 @deffnx {C Function} scm_strerror (err)
1126 Return the Unix error message corresponding to @var{err}, an integer
1129 When @code{setlocale} has been called (@pxref{Locales}), the message
1130 is in the language and charset of @code{LC_MESSAGES}. (This is done
1134 @c begin (scm-doc-string "boot-9.scm" "false-if-exception")
1135 @deffn syntax false-if-exception expr
1136 Returns the result of evaluating its argument; however
1137 if an exception occurs then @code{#f} is returned instead.
1143 @subsection Dynamic Wind
1145 For Scheme code, the fundamental procedure to react to non-local entry
1146 and exits of dynamic contexts is @code{dynamic-wind}. C code could
1147 use @code{scm_internal_dynamic_wind}, but since C does not allow the
1148 convenient construction of anonymous procedures that close over
1149 lexical variables, this will be, well, inconvenient.
1151 Therefore, Guile offers the functions @code{scm_dynwind_begin} and
1152 @code{scm_dynwind_end} to delimit a dynamic extent. Within this
1153 dynamic extent, which is calles a @dfn{dynwind context}, you can
1154 perform various @dfn{dynwind actions} that control what happens when
1155 the dynwind context is entered or left. For example, you can register
1156 a cleanup routine with @code{scm_dynwind_unwind_handler} that is
1157 executed when the context is left. There are several other more
1158 specialized dynwind actions as well, for example to temporarily block
1159 the execution of asyncs or to temporarily change the current output
1160 port. They are described elsewhere in this manual.
1162 Here is an example that shows how to prevent memory leaks.
1166 /* Suppose there is a function called FOO in some library that you
1167 would like to make available to Scheme code (or to C code that
1168 follows the Scheme conventions).
1170 FOO takes two C strings and returns a new string. When an error has
1171 occurred in FOO, it returns NULL.
1174 char *foo (char *s1, char *s2);
1176 /* SCM_FOO interfaces the C function FOO to the Scheme way of life.
1177 It takes care to free up all temporary strings in the case of
1182 scm_foo (SCM s1, SCM s2)
1184 char *c_s1, *c_s2, *c_res;
1186 scm_dynwind_begin (0);
1188 c_s1 = scm_to_locale_string (s1);
1190 /* Call 'free (c_s1)' when the dynwind context is left.
1192 scm_dynwind_unwind_handler (free, c_s1, SCM_F_WIND_EXPLICITLY);
1194 c_s2 = scm_to_locale_string (s2);
1196 /* Same as above, but more concisely.
1198 scm_dynwind_free (c_s2);
1200 c_res = foo (c_s1, c_s2);
1202 scm_memory_error ("foo");
1206 return scm_take_locale_string (res);
1210 @rnindex dynamic-wind
1211 @deffn {Scheme Procedure} dynamic-wind in_guard thunk out_guard
1212 @deffnx {C Function} scm_dynamic_wind (in_guard, thunk, out_guard)
1213 All three arguments must be 0-argument procedures.
1214 @var{in_guard} is called, then @var{thunk}, then
1217 If, any time during the execution of @var{thunk}, the
1218 dynamic extent of the @code{dynamic-wind} expression is escaped
1219 non-locally, @var{out_guard} is called. If the dynamic extent of
1220 the dynamic-wind is re-entered, @var{in_guard} is called. Thus
1221 @var{in_guard} and @var{out_guard} may be called any number of
1224 (define x 'normal-binding)
1226 (define a-cont (call-with-current-continuation
1232 (lambda () (set! x 'special-binding))
1236 (lambda () (display x) (newline)
1237 (call-with-current-continuation escape)
1238 (display x) (newline)
1243 (lambda () (set! x old-x)))))))
1250 @result{} normal-binding
1255 @result{} a-cont ;; the value of the (define a-cont...)
1257 @result{} normal-binding
1259 @result{} special-binding
1263 @deftp {C Type} scm_t_dynwind_flags
1264 This is an enumeration of several flags that modify the behavior of
1265 @code{scm_dynwind_begin}. The flags are listed in the following
1269 @item SCM_F_DYNWIND_REWINDABLE
1270 The dynamic context is @dfn{rewindable}. This means that it can be
1271 reentered non-locally (via the invokation of a continuation). The
1272 default is that a dynwind context can not be reentered non-locally.
1277 @deftypefn {C Function} void scm_dynwind_begin (scm_t_dynwind_flags flags)
1278 The function @code{scm_dynwind_begin} starts a new dynamic context and
1279 makes it the `current' one.
1281 The @var{flags} argument determines the default behavior of the
1282 context. Normally, use 0. This will result in a context that can not
1283 be reentered with a captured continuation. When you are prepared to
1284 handle reentries, include @code{SCM_F_DYNWIND_REWINDABLE} in
1287 Being prepared for reentry means that the effects of unwind handlers
1288 can be undone on reentry. In the example above, we want to prevent a
1289 memory leak on non-local exit and thus register an unwind handler that
1290 frees the memory. But once the memory is freed, we can not get it
1291 back on reentry. Thus reentry can not be allowed.
1293 The consequence is that continuations become less useful when
1294 non-reenterable contexts are captured, but you don't need to worry
1295 about that too much.
1297 The context is ended either implicitly when a non-local exit happens,
1298 or explicitly with @code{scm_dynwind_end}. You must make sure that a
1299 dynwind context is indeed ended properly. If you fail to call
1300 @code{scm_dynwind_end} for each @code{scm_dynwind_begin}, the behavior
1304 @deftypefn {C Function} void scm_dynwind_end ()
1305 End the current dynamic context explicitly and make the previous one
1309 @deftp {C Type} scm_t_wind_flags
1310 This is an enumeration of several flags that modify the behavior of
1311 @code{scm_dynwind_unwind_handler} and
1312 @code{scm_dynwind_rewind_handler}. The flags are listed in the
1316 @item SCM_F_WIND_EXPLICITLY
1317 @vindex SCM_F_WIND_EXPLICITLY
1318 The registered action is also carried out when the dynwind context is
1319 entered or left locally.
1323 @deftypefn {C Function} void scm_dynwind_unwind_handler (void (*func)(void *), void *data, scm_t_wind_flags flags)
1324 @deftypefnx {C Function} void scm_dynwind_unwind_handler_with_scm (void (*func)(SCM), SCM data, scm_t_wind_flags flags)
1325 Arranges for @var{func} to be called with @var{data} as its arguments
1326 when the current context ends implicitly. If @var{flags} contains
1327 @code{SCM_F_WIND_EXPLICITLY}, @var{func} is also called when the
1328 context ends explicitly with @code{scm_dynwind_end}.
1330 The function @code{scm_dynwind_unwind_handler_with_scm} takes care that
1331 @var{data} is protected from garbage collection.
1334 @deftypefn {C Function} void scm_dynwind_rewind_handler (void (*func)(void *), void *data, scm_t_wind_flags flags)
1335 @deftypefnx {C Function} void scm_dynwind_rewind_handler_with_scm (void (*func)(SCM), SCM data, scm_t_wind_flags flags)
1336 Arrange for @var{func} to be called with @var{data} as its argument when
1337 the current context is restarted by rewinding the stack. When @var{flags}
1338 contains @code{SCM_F_WIND_EXPLICITLY}, @var{func} is called immediately
1341 The function @code{scm_dynwind_rewind_handler_with_scm} takes care that
1342 @var{data} is protected from garbage collection.
1346 @node Handling Errors
1347 @subsection How to Handle Errors
1349 Error handling is based on @code{catch} and @code{throw}. Errors are
1350 always thrown with a @var{key} and four arguments:
1354 @var{key}: a symbol which indicates the type of error. The symbols used
1355 by libguile are listed below.
1358 @var{subr}: the name of the procedure from which the error is thrown, or
1362 @var{message}: a string (possibly language and system dependent)
1363 describing the error. The tokens @code{~A} and @code{~S} can be
1364 embedded within the message: they will be replaced with members of the
1365 @var{args} list when the message is printed. @code{~A} indicates an
1366 argument printed using @code{display}, while @code{~S} indicates an
1367 argument printed using @code{write}. @var{message} can also be
1368 @code{#f}, to allow it to be derived from the @var{key} by the error
1369 handler (may be useful if the @var{key} is to be thrown from both C and
1373 @var{args}: a list of arguments to be used to expand @code{~A} and
1374 @code{~S} tokens in @var{message}. Can also be @code{#f} if no
1375 arguments are required.
1378 @var{rest}: a list of any additional objects required. e.g., when the
1379 key is @code{'system-error}, this contains the C errno value. Can also
1380 be @code{#f} if no additional objects are required.
1383 In addition to @code{catch} and @code{throw}, the following Scheme
1384 facilities are available:
1386 @deffn {Scheme Procedure} display-error stack port subr message args rest
1387 @deffnx {C Function} scm_display_error (stack, port, subr, message, args, rest)
1388 Display an error message to the output port @var{port}.
1389 @var{stack} is the saved stack for the error, @var{subr} is
1390 the name of the procedure in which the error occurred and
1391 @var{message} is the actual error message, which may contain
1392 formatting instructions. These will format the arguments in
1393 the list @var{args} accordingly. @var{rest} is currently
1397 The following are the error keys defined by libguile and the situations
1398 in which they are used:
1402 @cindex @code{error-signal}
1403 @code{error-signal}: thrown after receiving an unhandled fatal signal
1404 such as SIGSEGV, SIGBUS, SIGFPE etc. The @var{rest} argument in the throw
1405 contains the coded signal number (at present this is not the same as the
1406 usual Unix signal number).
1409 @cindex @code{system-error}
1410 @code{system-error}: thrown after the operating system indicates an
1411 error condition. The @var{rest} argument in the throw contains the
1415 @cindex @code{numerical-overflow}
1416 @code{numerical-overflow}: numerical overflow.
1419 @cindex @code{out-of-range}
1420 @code{out-of-range}: the arguments to a procedure do not fall within the
1424 @cindex @code{wrong-type-arg}
1425 @code{wrong-type-arg}: an argument to a procedure has the wrong type.
1428 @cindex @code{wrong-number-of-args}
1429 @code{wrong-number-of-args}: a procedure was called with the wrong number
1433 @cindex @code{memory-allocation-error}
1434 @code{memory-allocation-error}: memory allocation error.
1437 @cindex @code{stack-overflow}
1438 @code{stack-overflow}: stack overflow error.
1441 @cindex @code{regular-expression-syntax}
1442 @code{regular-expression-syntax}: errors generated by the regular
1446 @cindex @code{misc-error}
1447 @code{misc-error}: other errors.
1451 @subsubsection C Support
1453 In the following C functions, @var{SUBR} and @var{MESSAGE} parameters
1454 can be @code{NULL} to give the effect of @code{#f} described above.
1456 @deftypefn {C Function} SCM scm_error (SCM @var{key}, char *@var{subr}, char *@var{message}, SCM @var{args}, SCM @var{rest})
1457 Throw an error, as per @code{scm-error} above.
1460 @deftypefn {C Function} void scm_syserror (char *@var{subr})
1461 @deftypefnx {C Function} void scm_syserror_msg (char *@var{subr}, char *@var{message}, SCM @var{args})
1462 Throw an error with key @code{system-error} and supply @code{errno} in
1463 the @var{rest} argument. For @code{scm_syserror} the message is
1464 generated using @code{strerror}.
1466 Care should be taken that any code in between the failing operation
1467 and the call to these routines doesn't change @code{errno}.
1470 @deftypefn {C Function} void scm_num_overflow (char *@var{subr})
1471 @deftypefnx {C Function} void scm_out_of_range (char *@var{subr}, SCM @var{bad_value})
1472 @deftypefnx {C Function} void scm_wrong_num_args (SCM @var{proc})
1473 @deftypefnx {C Function} void scm_wrong_type_arg (char *@var{subr}, int @var{argnum}, SCM @var{bad_value})
1474 @deftypefnx {C Function} void scm_memory_error (char *@var{subr})
1475 Throw an error with the various keys described above.
1477 For @code{scm_wrong_num_args}, @var{proc} should be a Scheme symbol
1478 which is the name of the procedure incorrectly invoked.
1483 @c TeX-master: "guile.texi"