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 @chapter Controlling the Flow of Program Execution
12 * begin:: Evaluating a sequence of expressions.
13 * if cond case:: Simple conditional evaluation.
14 * and or:: Conditional evaluation of a sequence.
15 * while do:: Iteration mechanisms.
16 * Continuations:: Continuations.
17 * Multiple Values:: Returning and accepting multiple values.
18 * Exceptions:: Throwing and catching exceptions.
19 * Error Reporting:: Procedures for signaling errors.
20 * Dynamic Wind:: Guarding against non-local entrance/exit.
21 * Frames:: Another way to handle non-localness
22 * Handling Errors:: How to handle errors in C code.
25 Scheme has a more general view of program flow than C, both locally and
28 Controlling the local flow of control involves things like gotos, loops,
29 calling functions and returning from them. Non-local control flow
30 refers to situations where the program jumps across one or more levels
31 of function activations without using the normal call or return
34 The primitive means of C for local control flow is the @code{goto}
35 statement, together with @code{if}. Loops done with @code{for},
36 @code{while} or @code{do} could in principle be rewritten with just
37 @code{goto} and @code{if}. In Scheme, the primitive means for local
38 control flow is the @emph{function call} (together with @code{if}).
39 Thus, the repetition of some computation in a loop is ultimately
40 implemented by a function that calls itself, that is, by recursion.
42 This approach is theoretically very powerful since it is easier to
43 reason formally about recursion than about gotos. In C, using
44 recursion exclusively would not be practical, tho, since it would eat
45 up the stack very quickly. In Scheme, however, it is practical:
46 function calls that appear in a @dfn{tail position} do not use any
47 additional stack space.
49 A function call is in a tail position when it is the last thing the
50 calling function does. The value returned by the called function is
51 immediately returned from the calling function. In the following
52 example, the call to @code{bar-1} is in a tail position, while the
53 call to @code{bar-2} is not. (The call to @code{1-} in @code{foo-2}
54 is in a tail position, tho.)
64 Thus, when you take care to recurse only in tail positions, the
65 recursion will only use constant stack space and will be as good as a
66 loop constructed from gotos.
68 Scheme offers a few syntactic abstractions (@code{do} and @dfn{named}
69 @code{let}) that make writing loops slightly easier.
71 But only Scheme functions can call other functions in a tail position:
72 C functions can not. This matters when you have, say, two functions
73 that call each other recursively to form a common loop. The following
74 (unrealistic) example shows how one might go about determing whether a
75 non-negative integer @var{n} is even or odd.
80 (else (my-odd? (1- n)))))
84 (else (my-even? (1- n)))))
87 Because the calls to @code{my-even?} and @code{my-odd?} are in tail
88 positions, these two procedures can be applied to arbitrary large
89 integers without overflowing the stack. (They will still take a lot
92 However, when one or both of the two procedures would be rewritten in
93 C, it could no longer call its companion in a tail position (since C
94 does not have this concept). You might need to take this
95 consideration into account when deciding which parts of your program
96 to write in Scheme and which in C.
98 In addition to calling functions and returning from them, a Scheme
99 program can also exit non-locally from a function so that the control
100 flow returns directly to an outer level. This means that some functions
101 might not return at all.
103 Even more, it is not only possible to jump to some outer level of
104 control, a Scheme program can also jump back into the middle of a
105 function that has already exited. This might cause some functions to
106 return more than once.
108 In general, these non-local jumps are done by invoking
109 @dfn{continuations} that have previously been captured using
110 @code{call-with-current-continuation}. Guile also offers a slightly
111 restricted set of functions, @code{catch} and @code{throw}, that can
112 only be used for non-local exits. This restriction makes them more
113 efficient. Error reporting (with the function @code{error}) is
114 implemented by invoking @code{throw}, for example. The functions
115 @code{catch} and @code{throw} belong to the topic of @dfn{exceptions}.
117 Since Scheme functions can call C functions and vice versa, C code can
118 experience the more general control flow of Scheme as well. It is
119 possible that a C function will not return at all, or will return more
120 than once. While C does offer @code{setjmp} and @code{longjmp} for
121 non-local exits, it is still an unusual thing for C code. In
122 contrast, non-local exits are very common in Scheme, mostly to report
125 You need to be prepared for the non-local jumps in the control flow
126 whenever you use a function from @code{libguile}: it is best to assume
127 that any @code{libguile} function might signal an error or run a pending
128 signal handler (which in turn can do arbitrary things).
130 It is often necessary to take cleanup actions when the control leaves a
131 function non-locally. Also, when the control returns non-locally, some
132 setup actions might be called for. For example, the Scheme function
133 @code{with-output-to-port} needs to modify the global state so that
134 @code{current-output-port} returns the port passed to
135 @code{with-output-to-port}. The global output port needs to be reset to
136 its previous value when @code{with-output-to-port} returns normally or
137 when it is exited non-locally. Likewise, the port needs to be set again
138 when control enters non-locally.
140 Scheme code can use the @code{dynamic-wind} function to arrange for
141 the setting and resetting of the global state. C code could use the
142 corresponding @code{scm_internal_dynamic_wind} function, but it might
143 prefer to use the @dfn{frames} concept that is more natural for C
148 @section Evaluating a Sequence of Expressions
152 @cindex expression sequencing
154 The @code{begin} syntax is used for grouping several expressions
155 together so that they are treated as if they were one expression.
156 This is particularly important when syntactic expressions are used
157 which only allow one expression, but the programmer wants to use more
158 than one expression in that place. As an example, consider the
159 conditional expression below:
163 (begin (display "greater") (newline)))
166 If the two calls to @code{display} and @code{newline} were not embedded
167 in a @code{begin}-statement, the call to @code{newline} would get
168 misinterpreted as the else-branch of the @code{if}-expression.
170 @deffn syntax begin expr1 expr2 @dots{}
171 The expression(s) are evaluated in left-to-right order and the value
172 of the last expression is returned as the value of the
173 @code{begin}-expression. This expression type is used when the
174 expressions before the last one are evaluated for their side effects.
176 Guile also allows the expression @code{(begin)}, a @code{begin} with no
177 sub-expressions. Such an expression returns the `unspecified' value.
181 @section Simple Conditional Evaluation
183 @cindex conditional evaluation
188 Guile provides three syntactic constructs for conditional evaluation.
189 @code{if} is the normal if-then-else expression (with an optional else
190 branch), @code{cond} is a conditional expression with multiple branches
191 and @code{case} branches if an expression has one of a set of constant
194 @deffn syntax if test consequent [alternate]
195 All arguments may be arbitrary expressions. First, @var{test} is
196 evaluated. If it returns a true value, the expression @var{consequent}
197 is evaluated and @var{alternate} is ignored. If @var{test} evaluates to
198 @code{#f}, @var{alternate} is evaluated instead. The value of the
199 evaluated branch (@var{consequent} or @var{alternate}) is returned as
200 the value of the @code{if} expression.
202 When @var{alternate} is omitted and the @var{test} evaluates to
203 @code{#f}, the value of the expression is not specified.
206 @deffn syntax cond clause1 clause2 @dots{}
207 Each @code{cond}-clause must look like this:
210 (@var{test} @var{expression} @dots{})
213 where @var{test} and @var{expression} are arbitrary expression, or like
217 (@var{test} => @var{expression})
220 where @var{expression} must evaluate to a procedure.
222 The @var{test}s of the clauses are evaluated in order and as soon as one
223 of them evaluates to a true values, the corresponding @var{expression}s
224 are evaluated in order and the last value is returned as the value of
225 the @code{cond}-expression. For the @code{=>} clause type,
226 @var{expression} is evaluated and the resulting procedure is applied to
227 the value of @var{test}. The result of this procedure application is
228 then the result of the @code{cond}-expression.
230 The @var{test} of the last @var{clause} may be the symbol @code{else}.
231 Then, if none of the preceding @var{test}s is true, the
232 @var{expression}s following the @code{else} are evaluated to produce the
233 result of the @code{cond}-expression.
236 @deffn syntax case key clause1 clause2 @dots{}
237 @var{key} may be any expression, the @var{clause}s must have the form
240 ((@var{datum1} @dots{}) @var{expr1} @var{expr2} @dots{})
243 and the last @var{clause} may have the form
246 (else @var{expr1} @var{expr2} @dots{})
249 All @var{datum}s must be distinct. First, @var{key} is evaluated. The
250 the result of this evaluation is compared against all @var{datum}s using
251 @code{eqv?}. When this comparison succeeds, the expression(s) following
252 the @var{datum} are evaluated from left to right, returning the value of
253 the last expression as the result of the @code{case} expression.
255 If the @var{key} matches no @var{datum} and there is an
256 @code{else}-clause, the expressions following the @code{else} are
257 evaluated. If there is no such clause, the result of the expression is
263 @section Conditional Evaluation of a Sequence of Expressions
265 @code{and} and @code{or} evaluate all their arguments in order, similar
266 to @code{begin}, but evaluation stops as soon as one of the expressions
267 evaluates to false or true, respectively.
269 @deffn syntax and expr @dots{}
270 Evaluate the @var{expr}s from left to right and stop evaluation as soon
271 as one expression evaluates to @code{#f}; the remaining expressions are
272 not evaluated. The value of the last evaluated expression is returned.
273 If no expression evaluates to @code{#f}, the value of the last
274 expression is returned.
276 If used without expressions, @code{#t} is returned.
279 @deffn syntax or expr @dots{}
280 Evaluate the @var{expr}s from left to right and stop evaluation as soon
281 as one expression evaluates to a true value (that is, a value different
282 from @code{#f}); the remaining expressions are not evaluated. The value
283 of the last evaluated expression is returned. If all expressions
284 evaluate to @code{#f}, @code{#f} is returned.
286 If used without expressions, @code{#f} is returned.
291 @section Iteration mechanisms
297 Scheme has only few iteration mechanisms, mainly because iteration in
298 Scheme programs is normally expressed using recursion. Nevertheless,
299 R5RS defines a construct for programming loops, calling @code{do}. In
300 addition, Guile has an explicit looping syntax called @code{while}.
302 @deffn syntax do ((variable init [step]) @dots{}) (test [expr @dots{}]) body @dots{}
303 Bind @var{variable}s and evaluate @var{body} until @var{test} is true.
304 The return value is the last @var{expr} after @var{test}, if given. A
305 simple example will illustrate the basic form,
315 Or with two variables and a final return value,
322 (format #t "3**~s is ~s\n" i p))
332 The @var{variable} bindings are established like a @code{let}, in that
333 the expressions are all evaluated and then all bindings made. When
334 iterating, the optional @var{step} expressions are evaluated with the
335 previous bindings in scope, then new bindings all made.
337 The @var{test} expression is a termination condition. Looping stops
338 when the @var{test} is true. It's evaluated before running the
339 @var{body} each time, so if it's true the first time then @var{body}
342 The optional @var{expr}s after the @var{test} are evaluated at the end
343 of looping, with the final @var{variable} bindings available. The
344 last @var{expr} gives the return value, or if there are no @var{expr}s
345 the return value is unspecified.
347 Each iteration establishes bindings to fresh locations for the
348 @var{variable}s, like a new @code{let} for each iteration. This is
349 done for @var{variable}s without @var{step} expressions too. The
350 following illustrates this, showing how a new @code{i} is captured by
351 the @code{lambda} in each iteration (@pxref{About Closure,, The
352 Concept of Closure}).
358 (set! lst (cons (lambda () i) lst)))
359 (map (lambda (proc) (proc)) lst)
365 @deffn syntax while cond body @dots{}
366 Run a loop executing the @var{body} forms while @var{cond} is true.
367 @var{cond} is tested at the start of each iteration, so if it's
368 @code{#f} the first time then @var{body} is not executed at all. The
369 return value is unspecified.
371 Within @code{while}, two extra bindings are provided, they can be used
372 from both @var{cond} and @var{body}.
374 @deffn {Scheme Procedure} break
375 Break out of the @code{while} form.
378 @deffn {Scheme Procedure} continue
379 Abandon the current iteration, go back to the start and test
380 @var{cond} again, etc.
383 Each @code{while} form gets its own @code{break} and @code{continue}
384 procedures, operating on that @code{while}. This means when loops are
385 nested the outer @code{break} can be used to escape all the way out.
390 (let ((outer-break break))
397 Note that each @code{break} and @code{continue} procedure can only be
398 used within the dynamic extent of its @code{while}. Outside the
399 @code{while} their behaviour is unspecified.
403 Another very common way of expressing iteration in Scheme programs is
404 the use of the so-called @dfn{named let}.
406 Named let is a variant of @code{let} which creates a procedure and calls
407 it in one step. Because of the newly created procedure, named let is
408 more powerful than @code{do}--it can be used for iteration, but also
409 for arbitrary recursion.
411 @deffn syntax let variable bindings body
412 For the definition of @var{bindings} see the documentation about
413 @code{let} (@pxref{Local Bindings}).
415 Named @code{let} works as follows:
419 A new procedure which accepts as many arguments as are in @var{bindings}
420 is created and bound locally (using @code{let}) to @var{variable}. The
421 new procedure's formal argument names are the name of the
425 The @var{body} expressions are inserted into the newly created procedure.
428 The procedure is called with the @var{init} expressions as the formal
432 The next example implements a loop which iterates (by recursion) 1000
447 @section Continuations
448 @cindex continuations
450 A ``continuation'' is the code that will execute when a given function
451 or expression returns. For example, consider
456 (display (bar)) (newline)
460 The continuation from the call to @code{bar} comprises a
461 @code{display} of the value returned, a @code{newline} and an
462 @code{exit}. This can be expressed as a function of one argument.
466 (display r) (newline)
470 In Scheme, continuations are represented as special procedures just
471 like this. The special property is that when a continuation is called
472 it abandons the current program location and jumps directly to that
473 represented by the continuation.
475 A continuation is like a dynamic label, capturing at run-time a point
476 in program execution, including all the nested calls that have lead to
477 it, or rather the code that will execute when those calls return.
479 Continuations are created with the following functions.
481 @deffn {Scheme Procedure} call-with-current-continuation proc
482 @deffnx {Scheme Procedure} call/cc proc
483 @rnindex call-with-current-continuation
484 Capture the current continuation and call @code{(@var{proc}
485 @var{cont})} with it. The return value is the value returned by
486 @var{proc}, or when @code{(@var{cont} @var{value})} is later invoked,
487 the return is the @var{value} passed.
489 Normally @var{cont} should be called with one argument, but when the
490 location resumed is expecting multiple values (@pxref{Multiple
491 Values}) then they should be passed as multiple arguments, for
492 instance @code{(@var{cont} @var{x} @var{y} @var{z})}.
494 @var{cont} may only be used from the dynamic root in which it was
495 created (@pxref{Dynamic Roots}), and in a multi-threaded program only
496 from the thread in which it was created, since each thread is a
497 separate dynamic root.
499 The call to @var{proc} is not part of the continuation captured, it runs
500 only when the continuation is created. Often a program will want to
501 store @var{cont} somewhere for later use; this can be done in
504 The @code{call} in the name @code{call-with-current-continuation}
505 refers to the way a call to @var{proc} gives the newly created
506 continuation. It's not related to the way a call is used later to
507 invoke that continuation.
509 @code{call/cc} is an alias for @code{call-with-current-continuation}.
510 This is in common use since the latter is rather long.
513 @deftypefn {C Function} SCM scm_make_continuation (int *first)
514 Capture the current continuation as described above. The return value
515 is the new continuation, and @var{*first} is set to 1.
517 When the continuation is invoked, @code{scm_make_continuation} will
518 return again, this time returning the value (or set of multiple
519 values) passed in that invocation, and with @var{*first} set to 0.
524 Here is a simple example,
528 (format #t "the return is ~a\n"
532 @result{} the return is 1
535 @result{} the return is 2
538 @code{call/cc} captures a continuation in which the value returned is
539 going to be displayed by @code{format}. The @code{lambda} stores this
540 in @code{kont} and gives an initial return @code{1} which is
541 displayed. The later invocation of @code{kont} resumes the captured
542 point, but this time returning @code{2}, which is displayed.
544 When Guile is run interactively, a call to @code{format} like this has
545 an implicit return back to the read-eval-print loop. @code{call/cc}
546 captures that like any other return, which is why interactively
547 @code{kont} will come back to read more input.
550 C programmers may note that @code{call/cc} is like @code{setjmp} in
551 the way it records at runtime a point in program execution. A call to
552 a continuation is like a @code{longjmp} in that it abandons the
553 present location and goes to the recorded one. Like @code{longjmp},
554 the value passed to the continuation is the value returned by
555 @code{call/cc} on resuming there. However @code{longjmp} can only go
556 up the program stack, but the continuation mechanism can go anywhere.
558 When a continuation is invoked, @code{call/cc} and subsequent code
559 effectively ``returns'' a second time. It can be confusing to imagine
560 a function returning more times than it was called. It may help
561 instead to think of it being stealthily re-entered and then program
562 flow going on as normal.
564 The functions @code{dynamic-wind} (@pxref{Dynamic Wind}) can be used to
565 ensure setup and cleanup code is run when a program locus is resumed or
566 abandoned through the continuation mechanism. C code can use
567 @dfn{frames} (@pxref{Frames}).
570 Continuations are a powerful mechanism, and can be used to implement
571 almost any sort of control structure, such as loops, coroutines, or
574 However the implementation of continuations in Guile is not as
575 efficient as one might hope, because Guile is designed to cooperate
576 with programs written in other languages, such as C, which do not know
577 about continuations. Basically continuations are captured by a block
578 copy of the stack, and resumed by copying back.
580 For this reason, generally continuations should be used only when
581 there is no other simple way to achieve the desired result, or when
582 the elegance of the continuation mechanism outweighs the need for
585 Escapes upwards from loops or nested functions are generally best
586 handled with exceptions (@pxref{Exceptions}). Coroutines can be
587 efficiently implemented with cooperating threads (a thread holds a
588 full program stack but doesn't copy it around the way continuations
592 @node Multiple Values
593 @section Returning and Accepting Multiple Values
595 @cindex multiple values
598 Scheme allows a procedure to return more than one value to its caller.
599 This is quite different to other languages which only allow
600 single-value returns. Returning multiple values is different from
601 returning a list (or pair or vector) of values to the caller, because
602 conceptually not @emph{one} compound object is returned, but several
605 The primitive procedures for handling multiple values are @code{values}
606 and @code{call-with-values}. @code{values} is used for returning
607 multiple values from a procedure. This is done by placing a call to
608 @code{values} with zero or more arguments in tail position in a
609 procedure body. @code{call-with-values} combines a procedure returning
610 multiple values with a procedure which accepts these values as
614 @deffn {Scheme Procedure} values arg1 @dots{} argN
615 @deffnx {C Function} scm_values (args)
616 Delivers all of its arguments to its continuation. Except for
617 continuations created by the @code{call-with-values} procedure,
618 all continuations take exactly one value. The effect of
619 passing no value or more than one value to continuations that
620 were not created by @code{call-with-values} is unspecified.
622 For @code{scm_values}, @var{args} is a list of arguments and the
623 return is a multiple-values object which the caller can return. In
624 the current implementation that object shares structure with
625 @var{args}, so @var{args} should not be modified subsequently.
628 @rnindex call-with-values
629 @deffn {Scheme Procedure} call-with-values producer consumer
630 Calls its @var{producer} argument with no values and a
631 continuation that, when passed some values, calls the
632 @var{consumer} procedure with those values as arguments. The
633 continuation for the call to @var{consumer} is the continuation
634 of the call to @code{call-with-values}.
637 (call-with-values (lambda () (values 4 5))
643 (call-with-values * -)
648 In addition to the fundamental procedures described above, Guile has a
649 module which exports a syntax called @code{receive}, which is much more
650 convenient. If you want to use it in your programs, you have to load
651 the module @code{(ice-9 receive)} with the statement
654 (use-modules (ice-9 receive))
657 @deffn {library syntax} receive formals expr body @dots{}
658 Evaluate the expression @var{expr}, and bind the result values (zero or
659 more) to the formal arguments in the formal argument list @var{formals}.
660 @var{formals} must have the same syntax like the formal argument list
661 used in @code{lambda} (@pxref{Lambda}). After binding the variables,
662 the expressions in @var{body} @dots{} are evaluated in order.
668 @cindex error handling
669 @cindex exception handling
671 A common requirement in applications is to want to jump
672 @dfn{non-locally} from the depths of a computation back to, say, the
673 application's main processing loop. Usually, the place that is the
674 target of the jump is somewhere in the calling stack of procedures that
675 called the procedure that wants to jump back. For example, typical
676 logic for a key press driven application might look something like this:
680 read the next key press and call dispatch-key
683 lookup the key in a keymap and call an appropriate procedure,
687 interactively read the required file name, then call
691 check whether file exists; if not, jump back to main-loop
695 The jump back to @code{main-loop} could be achieved by returning through
696 the stack one procedure at a time, using the return value of each
697 procedure to indicate the error condition, but Guile (like most modern
698 programming languages) provides an additional mechanism called
699 @dfn{exception handling} that can be used to implement such jumps much
703 * Exception Terminology:: Different ways to say the same thing.
704 * Catch:: Setting up to catch exceptions.
705 * Throw:: Throwing an exception.
706 * Lazy Catch:: Catch without unwinding the stack.
707 * Exception Implementation:: How Guile implements exceptions.
711 @node Exception Terminology
712 @subsection Exception Terminology
714 There are several variations on the terminology for dealing with
715 non-local jumps. It is useful to be aware of them, and to realize
716 that they all refer to the same basic mechanism.
720 Actually making a non-local jump may be called @dfn{raising an
721 exception}, @dfn{raising a signal}, @dfn{throwing an exception} or
722 @dfn{doing a long jump}. When the jump indicates an error condition,
723 people may talk about @dfn{signalling}, @dfn{raising} or @dfn{throwing}
727 Handling the jump at its target may be referred to as @dfn{catching} or
728 @dfn{handling} the @dfn{exception}, @dfn{signal} or, where an error
729 condition is involved, @dfn{error}.
732 Where @dfn{signal} and @dfn{signalling} are used, special care is needed
733 to avoid the risk of confusion with POSIX signals.
735 This manual prefers to speak of throwing and catching exceptions, since
736 this terminology matches the corresponding Guile primitives.
740 @subsection Catching Exceptions
742 @code{catch} is used to set up a target for a possible non-local jump.
743 The arguments of a @code{catch} expression are a @dfn{key}, which
744 restricts the set of exceptions to which this @code{catch} applies, a
745 thunk that specifies the code to execute and a @dfn{handler} procedure
746 that says what to do if an exception is thrown while executing the code.
747 Note that if the execution thunk executes @dfn{normally}, which means
748 without throwing any exceptions, the handler procedure is not called at
751 When an exception is thrown using the @code{throw} function, the first
752 argument of the @code{throw} is a symbol that indicates the type of the
753 exception. For example, Guile throws an exception using the symbol
754 @code{numerical-overflow} to indicate numerical overflow errors such as
760 ABORT: (numerical-overflow)
763 The @var{key} argument in a @code{catch} expression corresponds to this
764 symbol. @var{key} may be a specific symbol, such as
765 @code{numerical-overflow}, in which case the @code{catch} applies
766 specifically to exceptions of that type; or it may be @code{#t}, which
767 means that the @code{catch} applies to all exceptions, irrespective of
770 The second argument of a @code{catch} expression should be a thunk
771 (i.e. a procedure that accepts no arguments) that specifies the normal
772 case code. The @code{catch} is active for the execution of this thunk,
773 including any code called directly or indirectly by the thunk's body.
774 Evaluation of the @code{catch} expression activates the catch and then
777 The third argument of a @code{catch} expression is a handler procedure.
778 If an exception is thrown, this procedure is called with exactly the
779 arguments specified by the @code{throw}. Therefore, the handler
780 procedure must be designed to accept a number of arguments that
781 corresponds to the number of arguments in all @code{throw} expressions
782 that can be caught by this @code{catch}.
784 @deffn {Scheme Procedure} catch key thunk handler
785 @deffnx {C Function} scm_catch (key, thunk, handler)
786 Invoke @var{thunk} in the dynamic context of @var{handler} for
787 exceptions matching @var{key}. If thunk throws to the symbol
788 @var{key}, then @var{handler} is invoked this way:
790 (handler key args ...)
793 @var{key} is a symbol or @code{#t}.
795 @var{thunk} takes no arguments. If @var{thunk} returns
796 normally, that is the return value of @code{catch}.
798 Handler is invoked outside the scope of its own @code{catch}.
799 If @var{handler} again throws to the same key, a new handler
800 from further up the call chain is invoked.
802 If the key is @code{#t}, then a throw to @emph{any} symbol will
803 match this call to @code{catch}.
806 If the handler procedure needs to match a variety of @code{throw}
807 expressions with varying numbers of arguments, you should write it like
816 The @var{key} argument is guaranteed always to be present, because a
817 @code{throw} without a @var{key} is not valid. The number and
818 interpretation of the @var{args} varies from one type of exception to
819 another, but should be specified by the documentation for each exception
822 Note that, once the handler procedure is invoked, the catch that led to
823 the handler procedure being called is no longer active. Therefore, if
824 the handler procedure itself throws an exception, that exception can
825 only be caught by another active catch higher up the call stack, if
829 @deftypefn {C Function} SCM scm_internal_catch (SCM tag, scm_t_catch_body body, void *body_data, scm_t_catch_handler handler, void *handler_data)
830 The above @code{scm_catch} takes Scheme procedures as body and handler
831 arguments. @code{scm_internal_catch} is an equivalent taking C
834 @var{body} is called as @code{@var{body} (@var{body_data})} with a
835 catch on exceptions of the given @var{tag} type. If an exception is
836 caught, @var{handler} is called @code{@var{handler}
837 (@var{handler_data}, @var{key}, @var{args})}. @var{key} and
838 @var{args} are the @code{SCM} key and argument list from the
841 @tpindex scm_t_catch_body
842 @tpindex scm_t_catch_handler
843 @var{body} and @var{handler} should have the following prototypes.
844 @code{scm_t_catch_body} and @code{scm_t_catch_handler} are pointer
848 SCM body (void *data);
849 SCM handler (void *data, SCM key, SCM args);
852 The @var{body_data} and @var{handler_data} parameters are passed to
853 the respective calls so an application can communicate extra
854 information to those functions.
856 If the data consists of an @code{SCM} object, care should be taken
857 that it isn't garbage collected while still required. If the
858 @code{SCM} is a local C variable, one way to protect it is to pass a
859 pointer to that variable as the data parameter, since the C compiler
860 will then know the value must be held on the stack. Another way is to
861 use @code{scm_remember_upto_here_1} (@pxref{Remembering During
867 @subsection Throwing Exceptions
869 The @code{throw} primitive is used to throw an exception. One argument,
870 the @var{key}, is mandatory, and must be a symbol; it indicates the type
871 of exception that is being thrown. Following the @var{key},
872 @code{throw} accepts any number of additional arguments, whose meaning
873 depends on the exception type. The documentation for each possible type
874 of exception should specify the additional arguments that are expected
875 for that kind of exception.
877 @deffn {Scheme Procedure} throw key . args
878 @deffnx {C Function} scm_throw (key, args)
879 Invoke the catch form matching @var{key}, passing @var{args} to the
882 @var{key} is a symbol. It will match catches of the same symbol or of
885 If there is no handler at all, Guile prints an error and then exits.
888 When an exception is thrown, it will be caught by the innermost
889 @code{catch} expression that applies to the type of the thrown
890 exception; in other words, the innermost @code{catch} whose @var{key} is
891 @code{#t} or is the same symbol as that used in the @code{throw}
892 expression. Once Guile has identified the appropriate @code{catch}, it
893 handles the exception by applying that @code{catch} expression's handler
894 procedure to the arguments of the @code{throw}.
896 If there is no appropriate @code{catch} for a thrown exception, Guile
897 prints an error to the current error port indicating an uncaught
898 exception, and then exits. In practice, it is quite difficult to
899 observe this behaviour, because Guile when used interactively installs a
900 top level @code{catch} handler that will catch all exceptions and print
901 an appropriate error message @emph{without} exiting. For example, this
902 is what happens if you try to throw an unhandled exception in the
903 standard Guile REPL; note that Guile's command loop continues after the
907 guile> (throw 'badex)
908 <unnamed port>:3:1: In procedure gsubr-apply @dots{}
909 <unnamed port>:3:1: unhandled-exception: badex
914 The default uncaught exception behaviour can be observed by evaluating a
915 @code{throw} expression from the shell command line:
918 $ guile -c "(begin (throw 'badex) (display \"here\\n\"))"
919 guile: uncaught throw to badex: ()
924 That Guile exits immediately following the uncaught exception
925 is shown by the absence of any output from the @code{display}
926 expression, because Guile never gets to the point of evaluating that
931 @subsection Catch Without Unwinding
933 A @dfn{lazy catch} is used in the same way as a normal @code{catch},
934 with @var{key}, @var{thunk} and @var{handler} arguments specifying the
935 exception type, normal case code and handler procedure, but differs in
936 one important respect: the handler procedure is executed without
937 unwinding the call stack from the context of the @code{throw} expression
938 that caused the handler to be invoked.
940 @deffn {Scheme Procedure} lazy-catch key thunk handler
941 @deffnx {C Function} scm_lazy_catch (key, thunk, handler)
942 This behaves exactly like @code{catch}, except that it does
943 not unwind the stack before invoking @var{handler}.
944 The @var{handler} procedure is not allowed to return:
945 it must throw to another catch, or otherwise exit non-locally.
948 @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)
949 The above @code{scm_lazy_catch} takes Scheme procedures as body and
950 handler arguments. @code{scm_internal_lazy_catch} is an equivalent
951 taking C functions. See @code{scm_internal_catch} (@pxref{Catch}) for
952 a description of the parameters, the behaviour however of course
953 follows @code{lazy-catch}.
956 Typically, @var{handler} should save any desired state associated with
957 the stack at the point where the corresponding @code{throw} occurred,
958 and then throw an exception itself --- usually the same exception as the
959 one it caught. If @var{handler} is invoked and does @emph{not} throw an
960 exception, Guile itself throws an exception with key @code{misc-error}.
962 Not unwinding the stack means that throwing an exception that is caught
963 by a @code{lazy-catch} is @emph{almost} equivalent to calling the
964 @code{lazy-catch}'s handler inline instead of each @code{throw}, and
965 then omitting the surrounding @code{lazy-catch}. In other words,
969 (lambda () @dots{} (throw 'key args @dots{}) @dots{})
974 is @emph{almost} equivalent to
977 ((lambda () @dots{} (handler 'key args @dots{}) @dots{}))
981 But why only @emph{almost}? The difference is that with
982 @code{lazy-catch} (as with normal @code{catch}), the dynamic context is
983 unwound back to just outside the @code{lazy-catch} expression before
984 invoking the handler. (For an introduction to what is meant by dynamic
985 context, @xref{Dynamic Wind}.)
987 Then, when the handler @emph{itself} throws an exception, that exception
988 must be caught by some kind of @code{catch} (including perhaps another
989 @code{lazy-catch}) higher up the call stack.
991 The dynamic context also includes @code{with-fluids} blocks (REFFIXME),
992 so the effect of unwinding the dynamic context can also be seen in fluid
993 variable values. This is illustrated by the following code, in which
994 the normal case thunk uses @code{with-fluids} to temporarily change the
998 (define f (make-fluid))
999 (fluid-set! f "top level value")
1001 (define (handler . args)
1002 (cons (fluid-ref f) args))
1006 (with-fluids ((f "local value"))
1010 ("top level value" foo)
1013 (with-fluids ((f "local value"))
1020 In the @code{lazy-catch} version, the unwinding of dynamic context
1021 restores @code{f} to its value outside the @code{with-fluids} block
1022 before the handler is invoked, so the handler's @code{(fluid-ref f)}
1023 returns the external value.
1025 @code{lazy-catch} is useful because it permits the implementation of
1026 debuggers and other reflective programming tools that need to access the
1027 state of the call stack at the exact point where an exception or an
1028 error is thrown. For an example of this, see REFFIXME:stack-catch.
1031 @node Exception Implementation
1032 @subsection How Guile Implements Exceptions
1034 It is traditional in Scheme to implement exception systems using
1035 @code{call-with-current-continuation}. Continuations
1036 (@pxref{Continuations}) are such a powerful concept that any other
1037 control mechanism --- including @code{catch} and @code{throw} --- can be
1038 implemented in terms of them.
1040 Guile does not implement @code{catch} and @code{throw} like this,
1041 though. Why not? Because Guile is specifically designed to be easy to
1042 integrate with applications written in C. In a mixed Scheme/C
1043 environment, the concept of @dfn{continuation} must logically include
1044 ``what happens next'' in the C parts of the application as well as the
1045 Scheme parts, and it turns out that the only reasonable way of
1046 implementing continuations like this is to save and restore the complete
1049 So Guile's implementation of @code{call-with-current-continuation} is a
1050 stack copying one. This allows it to interact well with ordinary C
1051 code, but means that creating and calling a continuation is slowed down
1052 by the time that it takes to copy the C stack.
1054 The more targeted mechanism provided by @code{catch} and @code{throw}
1055 does not need to save and restore the C stack because the @code{throw}
1056 always jumps to a location higher up the stack of the code that executes
1057 the @code{throw}. Therefore Guile implements the @code{catch} and
1058 @code{throw} primitives independently of
1059 @code{call-with-current-continuation}, in a way that takes advantage of
1060 this @emph{upwards only} nature of exceptions.
1063 @node Error Reporting
1064 @section Procedures for Signaling Errors
1066 Guile provides a set of convenience procedures for signaling error
1067 conditions that are implemented on top of the exception primitives just
1070 @deffn {Scheme Procedure} error msg args @dots{}
1071 Raise an error with key @code{misc-error} and a message constructed by
1072 displaying @var{msg} and writing @var{args}.
1075 @deffn {Scheme Procedure} scm-error key subr message args data
1076 @deffnx {C Function} scm_error_scm (key, subr, message, args, data)
1077 Raise an error with key @var{key}. @var{subr} can be a string
1078 naming the procedure associated with the error, or @code{#f}.
1079 @var{message} is the error message string, possibly containing
1080 @code{~S} and @code{~A} escapes. When an error is reported,
1081 these are replaced by formatting the corresponding members of
1082 @var{args}: @code{~A} (was @code{%s} in older versions of
1083 Guile) formats using @code{display} and @code{~S} (was
1084 @code{%S}) formats using @code{write}. @var{data} is a list or
1085 @code{#f} depending on @var{key}: if @var{key} is
1086 @code{system-error} then it should be a list containing the
1087 Unix @code{errno} value; If @var{key} is @code{signal} then it
1088 should be a list containing the Unix signal number; otherwise
1089 it will usually be @code{#f}.
1092 @deffn {Scheme Procedure} strerror err
1093 @deffnx {C Function} scm_strerror (err)
1094 Return the Unix error message corresponding to @var{err}, which
1095 must be an integer value.
1098 @c begin (scm-doc-string "boot-9.scm" "false-if-exception")
1099 @deffn syntax false-if-exception expr
1100 Returns the result of evaluating its argument; however
1101 if an exception occurs then @code{#f} is returned instead.
1107 @section Dynamic Wind
1109 @rnindex dynamic-wind
1110 @deffn {Scheme Procedure} dynamic-wind in_guard thunk out_guard
1111 @deffnx {C Function} scm_dynamic_wind (in_guard, thunk, out_guard)
1112 All three arguments must be 0-argument procedures.
1113 @var{in_guard} is called, then @var{thunk}, then
1116 If, any time during the execution of @var{thunk}, the
1117 dynamic extent of the @code{dynamic-wind} expression is escaped
1118 non-locally, @var{out_guard} is called. If the dynamic extent of
1119 the dynamic-wind is re-entered, @var{in_guard} is called. Thus
1120 @var{in_guard} and @var{out_guard} may be called any number of
1123 (define x 'normal-binding)
1125 (define a-cont (call-with-current-continuation
1131 (lambda () (set! x 'special-binding))
1135 (lambda () (display x) (newline)
1136 (call-with-current-continuation escape)
1137 (display x) (newline)
1142 (lambda () (set! x old-x)))))))
1149 @result{} normal-binding
1154 @result{} a-cont ;; the value of the (define a-cont...)
1156 @result{} normal-binding
1158 @result{} special-binding
1165 For Scheme code, the fundamental procedure to react to non-local entry
1166 and exits of dynamic contexts is @code{dynamic-wind}. C code could use
1167 @code{scm_internal_dynamic_wind}, but since C does not allow the
1168 convenient construction of anonymous procedures that close over lexical
1169 variables, this will be, well, inconvenient. Instead, C code can use
1172 Guile offers the functions @code{scm_frame_begin} and
1173 @code{scm_frame_end} to delimit a dynamic extent. Within this dynamic
1174 extent, which is called a @dfn{frame}, you can perform various
1175 @dfn{frame actions} that control what happens when the frame is entered
1176 or left. For example, you can register a cleanup routine with
1177 @code{scm_frame_unwind} that is executed when the frame is left. There are
1178 several other more specialized frame actions as well, for example to
1179 temporarily block the execution of asyncs or to temporarily change the
1180 current output port. They are described elsewhere in this manual.
1182 Here is an example that shows how to prevent memory leaks.
1186 /* Suppose there is a function called FOO in some library that you
1187 would like to make available to Scheme code (or to C code that
1188 follows the Scheme conventions).
1190 FOO takes two C strings and returns a new string. When an error has
1191 occurred in FOO, it returns NULL.
1194 char *foo (char *s1, char *s2);
1196 /* SCM_FOO interfaces the C function FOO to the Scheme way of life.
1197 It takes care to free up all temporary strings in the case of
1200 It uses SCM_TO_STRING as a helper procedure.
1204 scm_to_string (SCM obj)
1206 if (SCM_STRINGP (obj))
1208 char *res = scm_malloc (SCM_STRING_LENGTH (obj)+1);
1209 strcpy (res, SCM_STRING_CHARS (obj));
1210 scm_remember_upto_here_1 (obj);
1214 scm_wrong_type_arg ("scm_to_string", 1, obj);
1218 scm_foo (SCM s1, SCM s2)
1220 char *c_s1, *c_s2, *c_res;
1222 scm_frame_begin (0);
1224 c_s1 = scm_to_string (s1);
1225 scm_frame_unwind_handler (free, c_s1, SCM_F_WIND_EXPLICITLY);
1227 c_s2 = scm_to_string (s2);
1228 scm_frame_unwind_handler (free, c_s2, SCM_F_WIND_EXPLICITLY);
1230 c_res = foo (c_s1, c_s2);
1232 scm_memory_error ("foo");
1236 return scm_take0str (res);
1240 @deftp {C Type} scm_t_frame_flags
1241 This is an enumeration of several flags that modify the behavior of
1242 @code{scm_begin_frame}. The flags are listed in the following table.
1245 @item SCM_F_FRAME_REWINDABLE
1246 The frame is @dfn{rewindable}. This means that it can be reentered
1247 non-locally (via the invokation of a continuation). The default is that
1248 a frame can not be reentered non-locally.
1253 @deftypefn {C Function} void scm_frame_begin (scm_t_frame_flags flags)
1254 The function @code{scm_begin_frame} starts a new frame and makes it the
1257 The @var{flags} argument determines the default behavior of the frame.
1258 For normal frames, use 0. This will result in a frame that can not be
1259 reentered with a captured continuation. When you are prepared to handle
1260 reentries, include @code{SCM_F_FRAME_REWINDABLE} in @var{flags}.
1262 Being prepared for reentry means that the effects of unwind handlers
1263 can be undone on reentry. In the example above, we want to prevent a
1264 memory leak on non-local exit and thus register an unwind handler that
1265 frees the memory. But once the memory is freed, we can not get it
1266 back on reentry. Thus reentry can not be allowed.
1268 The consequence is that continuations become less useful when
1269 non-reenterable frames are captured, but you don't need to worry about
1272 The frame is ended either implicitly when a non-local exit happens, or
1273 explicitly with @code{scm_end_frame}. You must make sure that a frame
1274 is indeed ended properly. If you fail to call @code{scm_end_frame}
1275 for each @code{scm_begin_frame}, the behavior is undefined.
1278 @deftypefn {C Function} void scm_frame_end ()
1279 End the current frame explicitly and make the previous frame current.
1282 @deftp {C Type} scm_t_wind_flags
1283 This is an enumeration of several flags that modify the behavior of
1284 @code{scm_on_unwind_handler} and @code{scm_on_rewind_handler}. The
1285 flags are listed in the following table.
1288 @item SCM_F_WIND_EXPLICITLY
1289 The registered action is also carried out when the frame is entered or
1294 @deftypefn {C Function} void scm_frame_unwind_handler (void (*func)(void *), void *data, scm_t_wind_flags flags)
1295 @deftypefnx {C Function} void scm_frame_unwind_handler_with_scm (void (*func)(SCM), SCM data, scm_t_wind_flags flags)
1296 Arranges for @var{func} to be called with @var{data} as its arguments
1297 when the current frame ends implicitly. If @var{flags} contains
1298 @code{SCM_F_WIND_EXPLICITLY}, @var{func} is also called when the frame
1299 ends explicitly with @code{scm_frame_end}.
1301 The function @code{scm_frame_unwind_handler_with_scm} takes care that
1302 @var{data} is protected from garbage collection.
1305 @deftypefn {C Function} void scm_frame_rewind_handler (void (*func)(void *), void *data, scm_t_wind_flags flags)
1306 @deftypefnx {C Function} void scm_frame_rewind_handler_with_scm (void (*func)(SCM), SCM data, scm_t_wind_flags flags)
1307 Arrange for @var{func} to be called with @var{data} as its argument when
1308 the current frame is restarted by rewinding the stack. When @var{flags}
1309 contains @code{SCM_F_WIND_EXPLICITLY}, @var{func} is called immediately
1312 The function @code{scm_frame_rewind_handler_with_scm} takes care that
1313 @var{data} is protected from garbage collection.
1317 @node Handling Errors
1318 @section How to Handle Errors
1320 Error handling is based on @code{catch} and @code{throw}. Errors are
1321 always thrown with a @var{key} and four arguments:
1325 @var{key}: a symbol which indicates the type of error. The symbols used
1326 by libguile are listed below.
1329 @var{subr}: the name of the procedure from which the error is thrown, or
1333 @var{message}: a string (possibly language and system dependent)
1334 describing the error. The tokens @code{~A} and @code{~S} can be
1335 embedded within the message: they will be replaced with members of the
1336 @var{args} list when the message is printed. @code{~A} indicates an
1337 argument printed using @code{display}, while @code{~S} indicates an
1338 argument printed using @code{write}. @var{message} can also be
1339 @code{#f}, to allow it to be derived from the @var{key} by the error
1340 handler (may be useful if the @var{key} is to be thrown from both C and
1344 @var{args}: a list of arguments to be used to expand @code{~A} and
1345 @code{~S} tokens in @var{message}. Can also be @code{#f} if no
1346 arguments are required.
1349 @var{rest}: a list of any additional objects required. e.g., when the
1350 key is @code{'system-error}, this contains the C errno value. Can also
1351 be @code{#f} if no additional objects are required.
1354 In addition to @code{catch} and @code{throw}, the following Scheme
1355 facilities are available:
1357 @deffn {Scheme Procedure} display-error stack port subr message args rest
1358 @deffnx {C Function} scm_display_error (stack, port, subr, message, args, rest)
1359 Display an error message to the output port @var{port}.
1360 @var{stack} is the saved stack for the error, @var{subr} is
1361 the name of the procedure in which the error occurred and
1362 @var{message} is the actual error message, which may contain
1363 formatting instructions. These will format the arguments in
1364 the list @var{args} accordingly. @var{rest} is currently
1368 The following are the error keys defined by libguile and the situations
1369 in which they are used:
1373 @cindex @code{error-signal}
1374 @code{error-signal}: thrown after receiving an unhandled fatal signal
1375 such as SIGSEGV, SIGBUS, SIGFPE etc. The @var{rest} argument in the throw
1376 contains the coded signal number (at present this is not the same as the
1377 usual Unix signal number).
1380 @cindex @code{system-error}
1381 @code{system-error}: thrown after the operating system indicates an
1382 error condition. The @var{rest} argument in the throw contains the
1386 @cindex @code{numerical-overflow}
1387 @code{numerical-overflow}: numerical overflow.
1390 @cindex @code{out-of-range}
1391 @code{out-of-range}: the arguments to a procedure do not fall within the
1395 @cindex @code{wrong-type-arg}
1396 @code{wrong-type-arg}: an argument to a procedure has the wrong type.
1399 @cindex @code{wrong-number-of-args}
1400 @code{wrong-number-of-args}: a procedure was called with the wrong number
1404 @cindex @code{memory-allocation-error}
1405 @code{memory-allocation-error}: memory allocation error.
1408 @cindex @code{stack-overflow}
1409 @code{stack-overflow}: stack overflow error.
1412 @cindex @code{regular-expression-syntax}
1413 @code{regular-expression-syntax}: errors generated by the regular
1417 @cindex @code{misc-error}
1418 @code{misc-error}: other errors.
1422 @subsection C Support
1424 In the following C functions, @var{SUBR} and @var{MESSAGE} parameters
1425 can be @code{NULL} to give the effect of @code{#f} described above.
1427 @deftypefn {C Function} SCM scm_error (SCM @var{key}, char *@var{subr}, char *@var{message}, SCM @var{args}, SCM @var{rest})
1428 Throw an error, as per @code{scm-error} above.
1431 @deftypefn {C Function} void scm_syserror (char *@var{subr})
1432 @deftypefnx {C Function} void scm_syserror_msg (char *@var{subr}, char *@var{message}, SCM @var{args})
1433 Throw an error with key @code{system-error} and supply @code{errno} in
1434 the @var{rest} argument. For @code{scm_syserror} the message is
1435 generated using @code{strerror}.
1437 Care should be taken that any code in between the failing operation
1438 and the call to these routines doesn't change @code{errno}.
1441 @deftypefn {C Function} void scm_num_overflow (char *@var{subr})
1442 @deftypefnx {C Function} void scm_out_of_range (char *@var{subr}, SCM @var{bad_value})
1443 @deftypefnx {C Function} void scm_wrong_num_args (SCM @var{proc})
1444 @deftypefnx {C Function} void scm_wrong_type_arg (char *@var{subr}, int @var{argnum}, SCM @var{bad_value})
1445 @deftypefnx {C Function} void scm_memory_error (char *@var{subr})
1446 Throw an error with the various keys described above.
1448 For @code{scm_wrong_num_args}, @var{proc} should be a Scheme symbol
1449 which is the name of the procedure incorrectly invoked.
1454 @c TeX-master: "guile.texi"