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:: Guarding against non-local entrance/exit.
24 * Frames:: Another way to handle non-localness
25 * Handling Errors:: How to handle errors in C code.
29 @subsection Evaluating a Sequence of Expressions
33 @cindex expression sequencing
35 The @code{begin} syntax is used for grouping several expressions
36 together so that they are treated as if they were one expression.
37 This is particularly important when syntactic expressions are used
38 which only allow one expression, but the programmer wants to use more
39 than one expression in that place. As an example, consider the
40 conditional expression below:
44 (begin (display "greater") (newline)))
47 If the two calls to @code{display} and @code{newline} were not embedded
48 in a @code{begin}-statement, the call to @code{newline} would get
49 misinterpreted as the else-branch of the @code{if}-expression.
51 @deffn syntax begin expr1 expr2 @dots{}
52 The expression(s) are evaluated in left-to-right order and the value
53 of the last expression is returned as the value of the
54 @code{begin}-expression. This expression type is used when the
55 expressions before the last one are evaluated for their side effects.
57 Guile also allows the expression @code{(begin)}, a @code{begin} with no
58 sub-expressions. Such an expression returns the `unspecified' value.
62 @subsection Simple Conditional Evaluation
64 @cindex conditional evaluation
69 Guile provides three syntactic constructs for conditional evaluation.
70 @code{if} is the normal if-then-else expression (with an optional else
71 branch), @code{cond} is a conditional expression with multiple branches
72 and @code{case} branches if an expression has one of a set of constant
75 @deffn syntax if test consequent [alternate]
76 All arguments may be arbitrary expressions. First, @var{test} is
77 evaluated. If it returns a true value, the expression @var{consequent}
78 is evaluated and @var{alternate} is ignored. If @var{test} evaluates to
79 @code{#f}, @var{alternate} is evaluated instead. The value of the
80 evaluated branch (@var{consequent} or @var{alternate}) is returned as
81 the value of the @code{if} expression.
83 When @var{alternate} is omitted and the @var{test} evaluates to
84 @code{#f}, the value of the expression is not specified.
87 @deffn syntax cond clause1 clause2 @dots{}
88 Each @code{cond}-clause must look like this:
91 (@var{test} @var{expression} @dots{})
94 where @var{test} and @var{expression} are arbitrary expression, or like
98 (@var{test} => @var{expression})
101 where @var{expression} must evaluate to a procedure.
103 The @var{test}s of the clauses are evaluated in order and as soon as one
104 of them evaluates to a true values, the corresponding @var{expression}s
105 are evaluated in order and the last value is returned as the value of
106 the @code{cond}-expression. For the @code{=>} clause type,
107 @var{expression} is evaluated and the resulting procedure is applied to
108 the value of @var{test}. The result of this procedure application is
109 then the result of the @code{cond}-expression.
111 The @var{test} of the last @var{clause} may be the symbol @code{else}.
112 Then, if none of the preceding @var{test}s is true, the
113 @var{expression}s following the @code{else} are evaluated to produce the
114 result of the @code{cond}-expression.
117 @deffn syntax case key clause1 clause2 @dots{}
118 @var{key} may be any expression, the @var{clause}s must have the form
121 ((@var{datum1} @dots{}) @var{expr1} @var{expr2} @dots{})
124 and the last @var{clause} may have the form
127 (else @var{expr1} @var{expr2} @dots{})
130 All @var{datum}s must be distinct. First, @var{key} is evaluated. The
131 the result of this evaluation is compared against all @var{datum}s using
132 @code{eqv?}. When this comparison succeeds, the expression(s) following
133 the @var{datum} are evaluated from left to right, returning the value of
134 the last expression as the result of the @code{case} expression.
136 If the @var{key} matches no @var{datum} and there is an
137 @code{else}-clause, the expressions following the @code{else} are
138 evaluated. If there is no such clause, the result of the expression is
144 @subsection Conditional Evaluation of a Sequence of Expressions
146 @code{and} and @code{or} evaluate all their arguments in order, similar
147 to @code{begin}, but evaluation stops as soon as one of the expressions
148 evaluates to false or true, respectively.
150 @deffn syntax and expr @dots{}
151 Evaluate the @var{expr}s from left to right and stop evaluation as soon
152 as one expression evaluates to @code{#f}; the remaining expressions are
153 not evaluated. The value of the last evaluated expression is returned.
154 If no expression evaluates to @code{#f}, the value of the last
155 expression is returned.
157 If used without expressions, @code{#t} is returned.
160 @deffn syntax or expr @dots{}
161 Evaluate the @var{expr}s from left to right and stop evaluation as soon
162 as one expression evaluates to a true value (that is, a value different
163 from @code{#f}); the remaining expressions are not evaluated. The value
164 of the last evaluated expression is returned. If all expressions
165 evaluate to @code{#f}, @code{#f} is returned.
167 If used without expressions, @code{#f} is returned.
172 @subsection Iteration mechanisms
178 Scheme has only few iteration mechanisms, mainly because iteration in
179 Scheme programs is normally expressed using recursion. Nevertheless,
180 R5RS defines a construct for programming loops, calling @code{do}. In
181 addition, Guile has an explicit looping syntax called @code{while}.
183 @deffn syntax do ((variable init [step]) @dots{}) (test [expr @dots{}]) body @dots{}
184 Bind @var{variable}s and evaluate @var{body} until @var{test} is true.
185 The return value is the last @var{expr} after @var{test}, if given. A
186 simple example will illustrate the basic form,
196 Or with two variables and a final return value,
203 (format #t "3**~s is ~s\n" i p))
213 The @var{variable} bindings are established like a @code{let}, in that
214 the expressions are all evaluated and then all bindings made. When
215 iterating, the optional @var{step} expressions are evaluated with the
216 previous bindings in scope, then new bindings all made.
218 The @var{test} expression is a termination condition. Looping stops
219 when the @var{test} is true. It's evaluated before running the
220 @var{body} each time, so if it's true the first time then @var{body}
223 The optional @var{expr}s after the @var{test} are evaluated at the end
224 of looping, with the final @var{variable} bindings available. The
225 last @var{expr} gives the return value, or if there are no @var{expr}s
226 the return value is unspecified.
228 Each iteration establishes bindings to fresh locations for the
229 @var{variable}s, like a new @code{let} for each iteration. This is
230 done for @var{variable}s without @var{step} expressions too. The
231 following illustrates this, showing how a new @code{i} is captured by
232 the @code{lambda} in each iteration (@pxref{About Closure,, The
233 Concept of Closure}).
239 (set! lst (cons (lambda () i) lst)))
240 (map (lambda (proc) (proc)) lst)
246 @deffn syntax while cond body @dots{}
247 Run a loop executing the @var{body} forms while @var{cond} is true.
248 @var{cond} is tested at the start of each iteration, so if it's
249 @code{#f} the first time then @var{body} is not executed at all. The
250 return value is unspecified.
252 Within @code{while}, two extra bindings are provided, they can be used
253 from both @var{cond} and @var{body}.
255 @deffn {Scheme Procedure} break
256 Break out of the @code{while} form.
259 @deffn {Scheme Procedure} continue
260 Abandon the current iteration, go back to the start and test
261 @var{cond} again, etc.
264 Each @code{while} form gets its own @code{break} and @code{continue}
265 procedures, operating on that @code{while}. This means when loops are
266 nested the outer @code{break} can be used to escape all the way out.
271 (let ((outer-break break))
278 Note that each @code{break} and @code{continue} procedure can only be
279 used within the dynamic extent of its @code{while}. Outside the
280 @code{while} their behaviour is unspecified.
284 Another very common way of expressing iteration in Scheme programs is
285 the use of the so-called @dfn{named let}.
287 Named let is a variant of @code{let} which creates a procedure and calls
288 it in one step. Because of the newly created procedure, named let is
289 more powerful than @code{do}--it can be used for iteration, but also
290 for arbitrary recursion.
292 @deffn syntax let variable bindings body
293 For the definition of @var{bindings} see the documentation about
294 @code{let} (@pxref{Local Bindings}).
296 Named @code{let} works as follows:
300 A new procedure which accepts as many arguments as are in @var{bindings}
301 is created and bound locally (using @code{let}) to @var{variable}. The
302 new procedure's formal argument names are the name of the
306 The @var{body} expressions are inserted into the newly created procedure.
309 The procedure is called with the @var{init} expressions as the formal
313 The next example implements a loop which iterates (by recursion) 1000
328 @subsection Continuations
329 @cindex continuations
331 A ``continuation'' is the code that will execute when a given function
332 or expression returns. For example, consider
337 (display (bar)) (newline)
341 The continuation from the call to @code{bar} comprises a
342 @code{display} of the value returned, a @code{newline} and an
343 @code{exit}. This can be expressed as a function of one argument.
347 (display r) (newline)
351 In Scheme, continuations are represented as special procedures just
352 like this. The special property is that when a continuation is called
353 it abandons the current program location and jumps directly to that
354 represented by the continuation.
356 A continuation is like a dynamic label, capturing at run-time a point
357 in program execution, including all the nested calls that have lead to
358 it (or rather the code that will execute when those calls return).
360 Continuations are created with the following functions.
362 @deffn {Scheme Procedure} call-with-current-continuation proc
363 @deffnx {Scheme Procedure} call/cc proc
364 @rnindex call-with-current-continuation
365 Capture the current continuation and call @code{(@var{proc}
366 @var{cont})} with it. The return value is the value returned by
367 @var{proc}, or when @code{(@var{cont} @var{value})} is later invoked,
368 the return is the @var{value} passed.
370 Normally @var{cont} should be called with one argument, but when the
371 location resumed is expecting multiple values (@pxref{Multiple
372 Values}) then they should be passed as multiple arguments, for
373 instance @code{(@var{cont} @var{x} @var{y} @var{z})}.
375 @var{cont} may only be used from the dynamic root in which it was
376 created (@pxref{Dynamic Roots}), and in a multi-threaded program only
377 from the thread in which it was created, since each thread is a
378 separate dynamic root.
380 The call to @var{proc} is not part of the continuation captured, it runs
381 only when the continuation is created. Often a program will want to
382 store @var{cont} somewhere for later use; this can be done in
385 The @code{call} in the name @code{call-with-current-continuation}
386 refers to the way a call to @var{proc} gives the newly created
387 continuation. It's not related to the way a call is used later to
388 invoke that continuation.
390 @code{call/cc} is an alias for @code{call-with-current-continuation}.
391 This is in common use since the latter is rather long.
394 @deftypefn {C Function} SCM scm_make_continuation (int *first)
395 Capture the current continuation as described above. The return value
396 is the new continuation, and @var{*first} is set to 1.
398 When the continuation is invoked, @code{scm_make_continuation} will
399 return again, this time returning the value (or set of multiple
400 values) passed in that invocation, and with @var{*first} set to 0.
405 Here is a simple example,
409 (format #t "the return is ~a\n"
413 @result{} the return is 1
416 @result{} the return is 2
419 @code{call/cc} captures a continuation in which the value returned is
420 going to be displayed by @code{format}. The @code{lambda} stores this
421 in @code{kont} and gives an initial return @code{1} which is
422 displayed. The later invocation of @code{kont} resumes the captured
423 point, but this time returning @code{2}, which is displayed.
425 When Guile is run interactively, a call to @code{format} like this has
426 an implicit return back to the read-eval-print loop. @code{call/cc}
427 captures that like any other return, which is why interactively
428 @code{kont} will come back to read more input.
431 C programmers may note that @code{call/cc} is like @code{setjmp} in
432 the way it records at runtime a point in program execution. A call to
433 a continuation is like a @code{longjmp} in that it abandons the
434 present location and goes to the recorded one. Like @code{longjmp},
435 the value passed to the continuation is the value returned by
436 @code{call/cc} on resuming there. However @code{longjmp} can only go
437 up the program stack, but the continuation mechanism can go anywhere.
439 When a continuation is invoked, @code{call/cc} and subsequent code
440 effectively ``returns'' a second time. It can be confusing to imagine
441 a function returning more times than it was called. It may help
442 instead to think of it being stealthily re-entered and then program
443 flow going on as normal.
445 @code{dynamic-wind} (@pxref{Dynamic Wind}) can be used to ensure setup
446 and cleanup code is run when a program locus is resumed or abandoned
447 through the continuation mechanism. C code can use @dfn{frames}
451 Continuations are a powerful mechanism, and can be used to implement
452 almost any sort of control structure, such as loops, coroutines, or
455 However the implementation of continuations in Guile is not as
456 efficient as one might hope, because Guile is designed to cooperate
457 with programs written in other languages, such as C, which do not know
458 about continuations. Basically continuations are captured by a block
459 copy of the stack, and resumed by copying back.
461 For this reason, generally continuations should be used only when
462 there is no other simple way to achieve the desired result, or when
463 the elegance of the continuation mechanism outweighs the need for
466 Escapes upwards from loops or nested functions are generally best
467 handled with exceptions (@pxref{Exceptions}). Coroutines can be
468 efficiently implemented with cooperating threads (a thread holds a
469 full program stack but doesn't copy it around the way continuations
473 @node Multiple Values
474 @subsection Returning and Accepting Multiple Values
476 @cindex multiple values
479 Scheme allows a procedure to return more than one value to its caller.
480 This is quite different to other languages which only allow
481 single-value returns. Returning multiple values is different from
482 returning a list (or pair or vector) of values to the caller, because
483 conceptually not @emph{one} compound object is returned, but several
486 The primitive procedures for handling multiple values are @code{values}
487 and @code{call-with-values}. @code{values} is used for returning
488 multiple values from a procedure. This is done by placing a call to
489 @code{values} with zero or more arguments in tail position in a
490 procedure body. @code{call-with-values} combines a procedure returning
491 multiple values with a procedure which accepts these values as
495 @deffn {Scheme Procedure} values arg1 @dots{} argN
496 @deffnx {C Function} scm_values (args)
497 Delivers all of its arguments to its continuation. Except for
498 continuations created by the @code{call-with-values} procedure,
499 all continuations take exactly one value. The effect of
500 passing no value or more than one value to continuations that
501 were not created by @code{call-with-values} is unspecified.
503 For @code{scm_values}, @var{args} is a list of arguments and the
504 return is a multiple-values object which the caller can return. In
505 the current implementation that object shares structure with
506 @var{args}, so @var{args} should not be modified subsequently.
509 @rnindex call-with-values
510 @deffn {Scheme Procedure} call-with-values producer consumer
511 Calls its @var{producer} argument with no values and a
512 continuation that, when passed some values, calls the
513 @var{consumer} procedure with those values as arguments. The
514 continuation for the call to @var{consumer} is the continuation
515 of the call to @code{call-with-values}.
518 (call-with-values (lambda () (values 4 5))
524 (call-with-values * -)
529 In addition to the fundamental procedures described above, Guile has a
530 module which exports a syntax called @code{receive}, which is much more
531 convenient. If you want to use it in your programs, you have to load
532 the module @code{(ice-9 receive)} with the statement
535 (use-modules (ice-9 receive))
538 @deffn {library syntax} receive formals expr body @dots{}
539 Evaluate the expression @var{expr}, and bind the result values (zero or
540 more) to the formal arguments in the formal argument list @var{formals}.
541 @var{formals} must have the same syntax like the formal argument list
542 used in @code{lambda} (@pxref{Lambda}). After binding the variables,
543 the expressions in @var{body} @dots{} are evaluated in order.
548 @subsection Exceptions
549 @cindex error handling
550 @cindex exception handling
552 A common requirement in applications is to want to jump
553 @dfn{non-locally} from the depths of a computation back to, say, the
554 application's main processing loop. Usually, the place that is the
555 target of the jump is somewhere in the calling stack of procedures that
556 called the procedure that wants to jump back. For example, typical
557 logic for a key press driven application might look something like this:
561 read the next key press and call dispatch-key
564 lookup the key in a keymap and call an appropriate procedure,
568 interactively read the required file name, then call
572 check whether file exists; if not, jump back to main-loop
576 The jump back to @code{main-loop} could be achieved by returning through
577 the stack one procedure at a time, using the return value of each
578 procedure to indicate the error condition, but Guile (like most modern
579 programming languages) provides an additional mechanism called
580 @dfn{exception handling} that can be used to implement such jumps much
584 * Exception Terminology:: Different ways to say the same thing.
585 * Catch:: Setting up to catch exceptions.
586 * Throw:: Throwing an exception.
587 * Lazy Catch:: Catch without unwinding the stack.
588 * Exception Implementation:: How Guile implements exceptions.
592 @node Exception Terminology
593 @subsubsection Exception Terminology
595 There are several variations on the terminology for dealing with
596 non-local jumps. It is useful to be aware of them, and to realize
597 that they all refer to the same basic mechanism.
601 Actually making a non-local jump may be called @dfn{raising an
602 exception}, @dfn{raising a signal}, @dfn{throwing an exception} or
603 @dfn{doing a long jump}. When the jump indicates an error condition,
604 people may talk about @dfn{signalling}, @dfn{raising} or @dfn{throwing}
608 Handling the jump at its target may be referred to as @dfn{catching} or
609 @dfn{handling} the @dfn{exception}, @dfn{signal} or, where an error
610 condition is involved, @dfn{error}.
613 Where @dfn{signal} and @dfn{signalling} are used, special care is needed
614 to avoid the risk of confusion with POSIX signals.
616 This manual prefers to speak of throwing and catching exceptions, since
617 this terminology matches the corresponding Guile primitives.
621 @subsubsection Catching Exceptions
623 @code{catch} is used to set up a target for a possible non-local jump.
624 The arguments of a @code{catch} expression are a @dfn{key}, which
625 restricts the set of exceptions to which this @code{catch} applies, a
626 thunk that specifies the code to execute and a @dfn{handler} procedure
627 that says what to do if an exception is thrown while executing the code.
628 Note that if the execution thunk executes @dfn{normally}, which means
629 without throwing any exceptions, the handler procedure is not called at
632 When an exception is thrown using the @code{throw} function, the first
633 argument of the @code{throw} is a symbol that indicates the type of the
634 exception. For example, Guile throws an exception using the symbol
635 @code{numerical-overflow} to indicate numerical overflow errors such as
641 ABORT: (numerical-overflow)
644 The @var{key} argument in a @code{catch} expression corresponds to this
645 symbol. @var{key} may be a specific symbol, such as
646 @code{numerical-overflow}, in which case the @code{catch} applies
647 specifically to exceptions of that type; or it may be @code{#t}, which
648 means that the @code{catch} applies to all exceptions, irrespective of
651 The second argument of a @code{catch} expression should be a thunk
652 (i.e. a procedure that accepts no arguments) that specifies the normal
653 case code. The @code{catch} is active for the execution of this thunk,
654 including any code called directly or indirectly by the thunk's body.
655 Evaluation of the @code{catch} expression activates the catch and then
658 The third argument of a @code{catch} expression is a handler procedure.
659 If an exception is thrown, this procedure is called with exactly the
660 arguments specified by the @code{throw}. Therefore, the handler
661 procedure must be designed to accept a number of arguments that
662 corresponds to the number of arguments in all @code{throw} expressions
663 that can be caught by this @code{catch}.
665 @deffn {Scheme Procedure} catch key thunk handler
666 @deffnx {C Function} scm_catch (key, thunk, handler)
667 Invoke @var{thunk} in the dynamic context of @var{handler} for
668 exceptions matching @var{key}. If thunk throws to the symbol
669 @var{key}, then @var{handler} is invoked this way:
671 (handler key args ...)
674 @var{key} is a symbol or @code{#t}.
676 @var{thunk} takes no arguments. If @var{thunk} returns
677 normally, that is the return value of @code{catch}.
679 Handler is invoked outside the scope of its own @code{catch}.
680 If @var{handler} again throws to the same key, a new handler
681 from further up the call chain is invoked.
683 If the key is @code{#t}, then a throw to @emph{any} symbol will
684 match this call to @code{catch}.
687 If the handler procedure needs to match a variety of @code{throw}
688 expressions with varying numbers of arguments, you should write it like
697 The @var{key} argument is guaranteed always to be present, because a
698 @code{throw} without a @var{key} is not valid. The number and
699 interpretation of the @var{args} varies from one type of exception to
700 another, but should be specified by the documentation for each exception
703 Note that, once the handler procedure is invoked, the catch that led to
704 the handler procedure being called is no longer active. Therefore, if
705 the handler procedure itself throws an exception, that exception can
706 only be caught by another active catch higher up the call stack, if
710 @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)
711 The above @code{scm_catch} takes Scheme procedures as body and handler
712 arguments. @code{scm_internal_catch} is an equivalent taking C
715 @var{body} is called as @code{@var{body} (@var{body_data})} with a
716 catch on exceptions of the given @var{tag} type. If an exception is
717 caught, @var{handler} is called @code{@var{handler}
718 (@var{handler_data}, @var{key}, @var{args})}. @var{key} and
719 @var{args} are the @code{SCM} key and argument list from the
722 @tpindex scm_t_catch_body
723 @tpindex scm_t_catch_handler
724 @var{body} and @var{handler} should have the following prototypes.
725 @code{scm_t_catch_body} and @code{scm_t_catch_handler} are pointer
729 SCM body (void *data);
730 SCM handler (void *data, SCM key, SCM args);
733 The @var{body_data} and @var{handler_data} parameters are passed to
734 the respective calls so an application can communicate extra
735 information to those functions.
737 If the data consists of an @code{SCM} object, care should be taken
738 that it isn't garbage collected while still required. If the
739 @code{SCM} is a local C variable, one way to protect it is to pass a
740 pointer to that variable as the data parameter, since the C compiler
741 will then know the value must be held on the stack. Another way is to
742 use @code{scm_remember_upto_here_1} (@pxref{Remembering During
748 @subsubsection Throwing Exceptions
750 The @code{throw} primitive is used to throw an exception. One argument,
751 the @var{key}, is mandatory, and must be a symbol; it indicates the type
752 of exception that is being thrown. Following the @var{key},
753 @code{throw} accepts any number of additional arguments, whose meaning
754 depends on the exception type. The documentation for each possible type
755 of exception should specify the additional arguments that are expected
756 for that kind of exception.
758 @deffn {Scheme Procedure} throw key . args
759 @deffnx {C Function} scm_throw (key, args)
760 Invoke the catch form matching @var{key}, passing @var{args} to the
763 @var{key} is a symbol. It will match catches of the same symbol or of
766 If there is no handler at all, Guile prints an error and then exits.
769 When an exception is thrown, it will be caught by the innermost
770 @code{catch} expression that applies to the type of the thrown
771 exception; in other words, the innermost @code{catch} whose @var{key} is
772 @code{#t} or is the same symbol as that used in the @code{throw}
773 expression. Once Guile has identified the appropriate @code{catch}, it
774 handles the exception by applying that @code{catch} expression's handler
775 procedure to the arguments of the @code{throw}.
777 If there is no appropriate @code{catch} for a thrown exception, Guile
778 prints an error to the current error port indicating an uncaught
779 exception, and then exits. In practice, it is quite difficult to
780 observe this behaviour, because Guile when used interactively installs a
781 top level @code{catch} handler that will catch all exceptions and print
782 an appropriate error message @emph{without} exiting. For example, this
783 is what happens if you try to throw an unhandled exception in the
784 standard Guile REPL; note that Guile's command loop continues after the
788 guile> (throw 'badex)
789 <unnamed port>:3:1: In procedure gsubr-apply @dots{}
790 <unnamed port>:3:1: unhandled-exception: badex
795 The default uncaught exception behaviour can be observed by evaluating a
796 @code{throw} expression from the shell command line:
799 $ guile -c "(begin (throw 'badex) (display \"here\\n\"))"
800 guile: uncaught throw to badex: ()
805 That Guile exits immediately following the uncaught exception
806 is shown by the absence of any output from the @code{display}
807 expression, because Guile never gets to the point of evaluating that
812 @subsubsection Catch Without Unwinding
814 A @dfn{lazy catch} is used in the same way as a normal @code{catch},
815 with @var{key}, @var{thunk} and @var{handler} arguments specifying the
816 exception type, normal case code and handler procedure, but differs in
817 one important respect: the handler procedure is executed without
818 unwinding the call stack from the context of the @code{throw} expression
819 that caused the handler to be invoked.
821 @deffn {Scheme Procedure} lazy-catch key thunk handler
822 @deffnx {C Function} scm_lazy_catch (key, thunk, handler)
823 This behaves exactly like @code{catch}, except that it does
824 not unwind the stack before invoking @var{handler}.
825 The @var{handler} procedure is not allowed to return:
826 it must throw to another catch, or otherwise exit non-locally.
829 @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)
830 The above @code{scm_lazy_catch} takes Scheme procedures as body and
831 handler arguments. @code{scm_internal_lazy_catch} is an equivalent
832 taking C functions. See @code{scm_internal_catch} (@pxref{Catch}) for
833 a description of the parameters, the behaviour however of course
834 follows @code{lazy-catch}.
837 Typically, @var{handler} should save any desired state associated with
838 the stack at the point where the corresponding @code{throw} occurred,
839 and then throw an exception itself --- usually the same exception as the
840 one it caught. If @var{handler} is invoked and does @emph{not} throw an
841 exception, Guile itself throws an exception with key @code{misc-error}.
843 Not unwinding the stack means that throwing an exception that is caught
844 by a @code{lazy-catch} is @emph{almost} equivalent to calling the
845 @code{lazy-catch}'s handler inline instead of each @code{throw}, and
846 then omitting the surrounding @code{lazy-catch}. In other words,
850 (lambda () @dots{} (throw 'key args @dots{}) @dots{})
855 is @emph{almost} equivalent to
858 ((lambda () @dots{} (handler 'key args @dots{}) @dots{}))
862 But why only @emph{almost}? The difference is that with
863 @code{lazy-catch} (as with normal @code{catch}), the dynamic context is
864 unwound back to just outside the @code{lazy-catch} expression before
865 invoking the handler. (For an introduction to what is meant by dynamic
866 context, @xref{Dynamic Wind}.)
868 Then, when the handler @emph{itself} throws an exception, that exception
869 must be caught by some kind of @code{catch} (including perhaps another
870 @code{lazy-catch}) higher up the call stack.
872 The dynamic context also includes @code{with-fluids} blocks (REFFIXME),
873 so the effect of unwinding the dynamic context can also be seen in fluid
874 variable values. This is illustrated by the following code, in which
875 the normal case thunk uses @code{with-fluids} to temporarily change the
879 (define f (make-fluid))
880 (fluid-set! f "top level value")
882 (define (handler . args)
883 (cons (fluid-ref f) args))
887 (with-fluids ((f "local value"))
891 ("top level value" foo)
894 (with-fluids ((f "local value"))
901 In the @code{lazy-catch} version, the unwinding of dynamic context
902 restores @code{f} to its value outside the @code{with-fluids} block
903 before the handler is invoked, so the handler's @code{(fluid-ref f)}
904 returns the external value.
906 @code{lazy-catch} is useful because it permits the implementation of
907 debuggers and other reflective programming tools that need to access the
908 state of the call stack at the exact point where an exception or an
909 error is thrown. For an example of this, see REFFIXME:stack-catch.
912 @node Exception Implementation
913 @subsubsection How Guile Implements Exceptions
915 It is traditional in Scheme to implement exception systems using
916 @code{call-with-current-continuation}. Continuations
917 (@pxref{Continuations}) are such a powerful concept that any other
918 control mechanism --- including @code{catch} and @code{throw} --- can be
919 implemented in terms of them.
921 Guile does not implement @code{catch} and @code{throw} like this,
922 though. Why not? Because Guile is specifically designed to be easy to
923 integrate with applications written in C. In a mixed Scheme/C
924 environment, the concept of @dfn{continuation} must logically include
925 ``what happens next'' in the C parts of the application as well as the
926 Scheme parts, and it turns out that the only reasonable way of
927 implementing continuations like this is to save and restore the complete
930 So Guile's implementation of @code{call-with-current-continuation} is a
931 stack copying one. This allows it to interact well with ordinary C
932 code, but means that creating and calling a continuation is slowed down
933 by the time that it takes to copy the C stack.
935 The more targeted mechanism provided by @code{catch} and @code{throw}
936 does not need to save and restore the C stack because the @code{throw}
937 always jumps to a location higher up the stack of the code that executes
938 the @code{throw}. Therefore Guile implements the @code{catch} and
939 @code{throw} primitives independently of
940 @code{call-with-current-continuation}, in a way that takes advantage of
941 this @emph{upwards only} nature of exceptions.
944 @node Error Reporting
945 @subsection Procedures for Signaling Errors
947 Guile provides a set of convenience procedures for signaling error
948 conditions that are implemented on top of the exception primitives just
951 @deffn {Scheme Procedure} error msg args @dots{}
952 Raise an error with key @code{misc-error} and a message constructed by
953 displaying @var{msg} and writing @var{args}.
956 @deffn {Scheme Procedure} scm-error key subr message args data
957 @deffnx {C Function} scm_error_scm (key, subr, message, args, data)
958 Raise an error with key @var{key}. @var{subr} can be a string
959 naming the procedure associated with the error, or @code{#f}.
960 @var{message} is the error message string, possibly containing
961 @code{~S} and @code{~A} escapes. When an error is reported,
962 these are replaced by formatting the corresponding members of
963 @var{args}: @code{~A} (was @code{%s} in older versions of
964 Guile) formats using @code{display} and @code{~S} (was
965 @code{%S}) formats using @code{write}. @var{data} is a list or
966 @code{#f} depending on @var{key}: if @var{key} is
967 @code{system-error} then it should be a list containing the
968 Unix @code{errno} value; If @var{key} is @code{signal} then it
969 should be a list containing the Unix signal number; otherwise
970 it will usually be @code{#f}.
973 @deffn {Scheme Procedure} strerror err
974 @deffnx {C Function} scm_strerror (err)
975 Return the Unix error message corresponding to @var{err}, which
976 must be an integer value.
979 @c begin (scm-doc-string "boot-9.scm" "false-if-exception")
980 @deffn syntax false-if-exception expr
981 Returns the result of evaluating its argument; however
982 if an exception occurs then @code{#f} is returned instead.
988 @subsection Dynamic Wind
990 @rnindex dynamic-wind
991 @deffn {Scheme Procedure} dynamic-wind in_guard thunk out_guard
992 @deffnx {C Function} scm_dynamic_wind (in_guard, thunk, out_guard)
993 All three arguments must be 0-argument procedures.
994 @var{in_guard} is called, then @var{thunk}, then
997 If, any time during the execution of @var{thunk}, the
998 dynamic extent of the @code{dynamic-wind} expression is escaped
999 non-locally, @var{out_guard} is called. If the dynamic extent of
1000 the dynamic-wind is re-entered, @var{in_guard} is called. Thus
1001 @var{in_guard} and @var{out_guard} may be called any number of
1004 (define x 'normal-binding)
1006 (define a-cont (call-with-current-continuation
1012 (lambda () (set! x 'special-binding))
1016 (lambda () (display x) (newline)
1017 (call-with-current-continuation escape)
1018 (display x) (newline)
1023 (lambda () (set! x old-x)))))))
1030 @result{} normal-binding
1035 @result{} a-cont ;; the value of the (define a-cont...)
1037 @result{} normal-binding
1039 @result{} special-binding
1046 For Scheme code, the fundamental procedure to react to non-local entry
1047 and exits of dynamic contexts is @code{dynamic-wind}. C code could use
1048 @code{scm_internal_dynamic_wind}, but since C does not allow the
1049 convenient construction of anonymous procedures that close over lexical
1050 variables, this will be, well, inconvenient. Instead, C code can use
1053 Guile offers the functions @code{scm_frame_begin} and
1054 @code{scm_frame_end} to delimit a dynamic extent. Within this dynamic
1055 extent, which is called a @dfn{frame}, you can perform various
1056 @dfn{frame actions} that control what happens when the frame is entered
1057 or left. For example, you can register a cleanup routine with
1058 @code{scm_frame_unwind} that is executed when the frame is left. There are
1059 several other more specialized frame actions as well, for example to
1060 temporarily block the execution of asyncs or to temporarily change the
1061 current output port. They are described elsewhere in this manual.
1063 Here is an example that shows how to prevent memory leaks.
1067 /* Suppose there is a function called FOO in some library that you
1068 would like to make available to Scheme code (or to C code that
1069 follows the Scheme conventions).
1071 FOO takes two C strings and returns a new string. When an error has
1072 occurred in FOO, it returns NULL.
1075 char *foo (char *s1, char *s2);
1077 /* SCM_FOO interfaces the C function FOO to the Scheme way of life.
1078 It takes care to free up all temporary strings in the case of
1083 scm_foo (SCM s1, SCM s2)
1085 char *c_s1, *c_s2, *c_res;
1087 scm_frame_begin (0);
1089 c_s1 = scm_to_locale_string (s1);
1091 /* Call 'free (c_s1)' when the frame is left.
1093 scm_frame_unwind_handler (free, c_s1, SCM_F_WIND_EXPLICITLY);
1095 c_s2 = scm_to_locale_string (s2);
1097 /* Same as above, but more concisely.
1099 scm_frame_free (c_s2);
1101 c_res = foo (c_s1, c_s2);
1103 scm_memory_error ("foo");
1107 return scm_take_locale_string (res);
1111 @deftp {C Type} scm_t_frame_flags
1112 This is an enumeration of several flags that modify the behavior of
1113 @code{scm_begin_frame}. The flags are listed in the following table.
1116 @item SCM_F_FRAME_REWINDABLE
1117 The frame is @dfn{rewindable}. This means that it can be reentered
1118 non-locally (via the invokation of a continuation). The default is that
1119 a frame can not be reentered non-locally.
1124 @deftypefn {C Function} void scm_frame_begin (scm_t_frame_flags flags)
1125 The function @code{scm_begin_frame} starts a new frame and makes it the
1128 The @var{flags} argument determines the default behavior of the frame.
1129 For normal frames, use 0. This will result in a frame that can not be
1130 reentered with a captured continuation. When you are prepared to handle
1131 reentries, include @code{SCM_F_FRAME_REWINDABLE} in @var{flags}.
1133 Being prepared for reentry means that the effects of unwind handlers
1134 can be undone on reentry. In the example above, we want to prevent a
1135 memory leak on non-local exit and thus register an unwind handler that
1136 frees the memory. But once the memory is freed, we can not get it
1137 back on reentry. Thus reentry can not be allowed.
1139 The consequence is that continuations become less useful when
1140 non-reenterable frames are captured, but you don't need to worry about
1143 The frame is ended either implicitly when a non-local exit happens, or
1144 explicitly with @code{scm_end_frame}. You must make sure that a frame
1145 is indeed ended properly. If you fail to call @code{scm_end_frame}
1146 for each @code{scm_begin_frame}, the behavior is undefined.
1149 @deftypefn {C Function} void scm_frame_end ()
1150 End the current frame explicitly and make the previous frame current.
1153 @deftp {C Type} scm_t_wind_flags
1154 This is an enumeration of several flags that modify the behavior of
1155 @code{scm_on_unwind_handler} and @code{scm_on_rewind_handler}. The
1156 flags are listed in the following table.
1159 @item SCM_F_WIND_EXPLICITLY
1160 @vindex SCM_F_WIND_EXPLICITLY
1161 The registered action is also carried out when the frame is entered or
1166 @deftypefn {C Function} void scm_frame_unwind_handler (void (*func)(void *), void *data, scm_t_wind_flags flags)
1167 @deftypefnx {C Function} void scm_frame_unwind_handler_with_scm (void (*func)(SCM), SCM data, scm_t_wind_flags flags)
1168 Arranges for @var{func} to be called with @var{data} as its arguments
1169 when the current frame ends implicitly. If @var{flags} contains
1170 @code{SCM_F_WIND_EXPLICITLY}, @var{func} is also called when the frame
1171 ends explicitly with @code{scm_frame_end}.
1173 The function @code{scm_frame_unwind_handler_with_scm} takes care that
1174 @var{data} is protected from garbage collection.
1177 @deftypefn {C Function} void scm_frame_rewind_handler (void (*func)(void *), void *data, scm_t_wind_flags flags)
1178 @deftypefnx {C Function} void scm_frame_rewind_handler_with_scm (void (*func)(SCM), SCM data, scm_t_wind_flags flags)
1179 Arrange for @var{func} to be called with @var{data} as its argument when
1180 the current frame is restarted by rewinding the stack. When @var{flags}
1181 contains @code{SCM_F_WIND_EXPLICITLY}, @var{func} is called immediately
1184 The function @code{scm_frame_rewind_handler_with_scm} takes care that
1185 @var{data} is protected from garbage collection.
1189 @node Handling Errors
1190 @subsection How to Handle Errors
1192 Error handling is based on @code{catch} and @code{throw}. Errors are
1193 always thrown with a @var{key} and four arguments:
1197 @var{key}: a symbol which indicates the type of error. The symbols used
1198 by libguile are listed below.
1201 @var{subr}: the name of the procedure from which the error is thrown, or
1205 @var{message}: a string (possibly language and system dependent)
1206 describing the error. The tokens @code{~A} and @code{~S} can be
1207 embedded within the message: they will be replaced with members of the
1208 @var{args} list when the message is printed. @code{~A} indicates an
1209 argument printed using @code{display}, while @code{~S} indicates an
1210 argument printed using @code{write}. @var{message} can also be
1211 @code{#f}, to allow it to be derived from the @var{key} by the error
1212 handler (may be useful if the @var{key} is to be thrown from both C and
1216 @var{args}: a list of arguments to be used to expand @code{~A} and
1217 @code{~S} tokens in @var{message}. Can also be @code{#f} if no
1218 arguments are required.
1221 @var{rest}: a list of any additional objects required. e.g., when the
1222 key is @code{'system-error}, this contains the C errno value. Can also
1223 be @code{#f} if no additional objects are required.
1226 In addition to @code{catch} and @code{throw}, the following Scheme
1227 facilities are available:
1229 @deffn {Scheme Procedure} display-error stack port subr message args rest
1230 @deffnx {C Function} scm_display_error (stack, port, subr, message, args, rest)
1231 Display an error message to the output port @var{port}.
1232 @var{stack} is the saved stack for the error, @var{subr} is
1233 the name of the procedure in which the error occurred and
1234 @var{message} is the actual error message, which may contain
1235 formatting instructions. These will format the arguments in
1236 the list @var{args} accordingly. @var{rest} is currently
1240 The following are the error keys defined by libguile and the situations
1241 in which they are used:
1245 @cindex @code{error-signal}
1246 @code{error-signal}: thrown after receiving an unhandled fatal signal
1247 such as SIGSEGV, SIGBUS, SIGFPE etc. The @var{rest} argument in the throw
1248 contains the coded signal number (at present this is not the same as the
1249 usual Unix signal number).
1252 @cindex @code{system-error}
1253 @code{system-error}: thrown after the operating system indicates an
1254 error condition. The @var{rest} argument in the throw contains the
1258 @cindex @code{numerical-overflow}
1259 @code{numerical-overflow}: numerical overflow.
1262 @cindex @code{out-of-range}
1263 @code{out-of-range}: the arguments to a procedure do not fall within the
1267 @cindex @code{wrong-type-arg}
1268 @code{wrong-type-arg}: an argument to a procedure has the wrong type.
1271 @cindex @code{wrong-number-of-args}
1272 @code{wrong-number-of-args}: a procedure was called with the wrong number
1276 @cindex @code{memory-allocation-error}
1277 @code{memory-allocation-error}: memory allocation error.
1280 @cindex @code{stack-overflow}
1281 @code{stack-overflow}: stack overflow error.
1284 @cindex @code{regular-expression-syntax}
1285 @code{regular-expression-syntax}: errors generated by the regular
1289 @cindex @code{misc-error}
1290 @code{misc-error}: other errors.
1294 @subsubsection C Support
1296 In the following C functions, @var{SUBR} and @var{MESSAGE} parameters
1297 can be @code{NULL} to give the effect of @code{#f} described above.
1299 @deftypefn {C Function} SCM scm_error (SCM @var{key}, char *@var{subr}, char *@var{message}, SCM @var{args}, SCM @var{rest})
1300 Throw an error, as per @code{scm-error} above.
1303 @deftypefn {C Function} void scm_syserror (char *@var{subr})
1304 @deftypefnx {C Function} void scm_syserror_msg (char *@var{subr}, char *@var{message}, SCM @var{args})
1305 Throw an error with key @code{system-error} and supply @code{errno} in
1306 the @var{rest} argument. For @code{scm_syserror} the message is
1307 generated using @code{strerror}.
1309 Care should be taken that any code in between the failing operation
1310 and the call to these routines doesn't change @code{errno}.
1313 @deftypefn {C Function} void scm_num_overflow (char *@var{subr})
1314 @deftypefnx {C Function} void scm_out_of_range (char *@var{subr}, SCM @var{bad_value})
1315 @deftypefnx {C Function} void scm_wrong_num_args (SCM @var{proc})
1316 @deftypefnx {C Function} void scm_wrong_type_arg (char *@var{subr}, int @var{argnum}, SCM @var{bad_value})
1317 @deftypefnx {C Function} void scm_memory_error (char *@var{subr})
1318 Throw an error with the various keys described above.
1320 For @code{scm_wrong_num_args}, @var{proc} should be a Scheme symbol
1321 which is the name of the procedure incorrectly invoked.
1326 @c TeX-master: "guile.texi"