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.
112 @cindex general cond clause
113 @cindex multiple values and cond
114 One additional @code{cond}-clause is available as an extension to
118 (@var{test} @var{guard} => @var{expression})
121 where @var{guard} and @var{expression} must evaluate to procedures.
122 For this clause type, @var{test} may return multiple values, and
123 @code{cond} ignores its boolean state; instead, @code{cond} evaluates
124 @var{guard} and applies the resulting procedure to the value(s) of
125 @var{test}, as if @var{guard} were the @var{consumer} argument of
126 @code{call-with-values}. Iff the result of that procedure call is a
127 true value, it evaluates @var{expression} and applies the resulting
128 procedure to the value(s) of @var{test}, in the same manner as the
129 @var{guard} was called.
131 The @var{test} of the last @var{clause} may be the symbol @code{else}.
132 Then, if none of the preceding @var{test}s is true, the
133 @var{expression}s following the @code{else} are evaluated to produce the
134 result of the @code{cond}-expression.
137 @deffn syntax case key clause1 clause2 @dots{}
138 @var{key} may be any expression, the @var{clause}s must have the form
141 ((@var{datum1} @dots{}) @var{expr1} @var{expr2} @dots{})
144 and the last @var{clause} may have the form
147 (else @var{expr1} @var{expr2} @dots{})
150 All @var{datum}s must be distinct. First, @var{key} is evaluated. The
151 the result of this evaluation is compared against all @var{datum}s using
152 @code{eqv?}. When this comparison succeeds, the expression(s) following
153 the @var{datum} are evaluated from left to right, returning the value of
154 the last expression as the result of the @code{case} expression.
156 If the @var{key} matches no @var{datum} and there is an
157 @code{else}-clause, the expressions following the @code{else} are
158 evaluated. If there is no such clause, the result of the expression is
164 @subsection Conditional Evaluation of a Sequence of Expressions
166 @code{and} and @code{or} evaluate all their arguments in order, similar
167 to @code{begin}, but evaluation stops as soon as one of the expressions
168 evaluates to false or true, respectively.
170 @deffn syntax and expr @dots{}
171 Evaluate the @var{expr}s from left to right and stop evaluation as soon
172 as one expression evaluates to @code{#f}; the remaining expressions are
173 not evaluated. The value of the last evaluated expression is returned.
174 If no expression evaluates to @code{#f}, the value of the last
175 expression is returned.
177 If used without expressions, @code{#t} is returned.
180 @deffn syntax or expr @dots{}
181 Evaluate the @var{expr}s from left to right and stop evaluation as soon
182 as one expression evaluates to a true value (that is, a value different
183 from @code{#f}); the remaining expressions are not evaluated. The value
184 of the last evaluated expression is returned. If all expressions
185 evaluate to @code{#f}, @code{#f} is returned.
187 If used without expressions, @code{#f} is returned.
192 @subsection Iteration mechanisms
198 Scheme has only few iteration mechanisms, mainly because iteration in
199 Scheme programs is normally expressed using recursion. Nevertheless,
200 R5RS defines a construct for programming loops, calling @code{do}. In
201 addition, Guile has an explicit looping syntax called @code{while}.
203 @deffn syntax do ((variable init [step]) @dots{}) (test [expr @dots{}]) body @dots{}
204 Bind @var{variable}s and evaluate @var{body} until @var{test} is true.
205 The return value is the last @var{expr} after @var{test}, if given. A
206 simple example will illustrate the basic form,
216 Or with two variables and a final return value,
223 (format #t "3**~s is ~s\n" i p))
233 The @var{variable} bindings are established like a @code{let}, in that
234 the expressions are all evaluated and then all bindings made. When
235 iterating, the optional @var{step} expressions are evaluated with the
236 previous bindings in scope, then new bindings all made.
238 The @var{test} expression is a termination condition. Looping stops
239 when the @var{test} is true. It's evaluated before running the
240 @var{body} each time, so if it's true the first time then @var{body}
243 The optional @var{expr}s after the @var{test} are evaluated at the end
244 of looping, with the final @var{variable} bindings available. The
245 last @var{expr} gives the return value, or if there are no @var{expr}s
246 the return value is unspecified.
248 Each iteration establishes bindings to fresh locations for the
249 @var{variable}s, like a new @code{let} for each iteration. This is
250 done for @var{variable}s without @var{step} expressions too. The
251 following illustrates this, showing how a new @code{i} is captured by
252 the @code{lambda} in each iteration (@pxref{About Closure,, The
253 Concept of Closure}).
259 (set! lst (cons (lambda () i) lst)))
260 (map (lambda (proc) (proc)) lst)
266 @deffn syntax while cond body @dots{}
267 Run a loop executing the @var{body} forms while @var{cond} is true.
268 @var{cond} is tested at the start of each iteration, so if it's
269 @code{#f} the first time then @var{body} is not executed at all. The
270 return value is unspecified.
272 Within @code{while}, two extra bindings are provided, they can be used
273 from both @var{cond} and @var{body}.
275 @deffn {Scheme Procedure} break
276 Break out of the @code{while} form.
279 @deffn {Scheme Procedure} continue
280 Abandon the current iteration, go back to the start and test
281 @var{cond} again, etc.
284 Each @code{while} form gets its own @code{break} and @code{continue}
285 procedures, operating on that @code{while}. This means when loops are
286 nested the outer @code{break} can be used to escape all the way out.
291 (let ((outer-break break))
298 Note that each @code{break} and @code{continue} procedure can only be
299 used within the dynamic extent of its @code{while}. Outside the
300 @code{while} their behaviour is unspecified.
304 Another very common way of expressing iteration in Scheme programs is
305 the use of the so-called @dfn{named let}.
307 Named let is a variant of @code{let} which creates a procedure and calls
308 it in one step. Because of the newly created procedure, named let is
309 more powerful than @code{do}--it can be used for iteration, but also
310 for arbitrary recursion.
312 @deffn syntax let variable bindings body
313 For the definition of @var{bindings} see the documentation about
314 @code{let} (@pxref{Local Bindings}).
316 Named @code{let} works as follows:
320 A new procedure which accepts as many arguments as are in @var{bindings}
321 is created and bound locally (using @code{let}) to @var{variable}. The
322 new procedure's formal argument names are the name of the
326 The @var{body} expressions are inserted into the newly created procedure.
329 The procedure is called with the @var{init} expressions as the formal
333 The next example implements a loop which iterates (by recursion) 1000
348 @subsection Continuations
349 @cindex continuations
351 A ``continuation'' is the code that will execute when a given function
352 or expression returns. For example, consider
357 (display (bar)) (newline)
361 The continuation from the call to @code{bar} comprises a
362 @code{display} of the value returned, a @code{newline} and an
363 @code{exit}. This can be expressed as a function of one argument.
367 (display r) (newline)
371 In Scheme, continuations are represented as special procedures just
372 like this. The special property is that when a continuation is called
373 it abandons the current program location and jumps directly to that
374 represented by the continuation.
376 A continuation is like a dynamic label, capturing at run-time a point
377 in program execution, including all the nested calls that have lead to
378 it (or rather the code that will execute when those calls return).
380 Continuations are created with the following functions.
382 @deffn {Scheme Procedure} call-with-current-continuation proc
383 @deffnx {Scheme Procedure} call/cc proc
384 @rnindex call-with-current-continuation
385 Capture the current continuation and call @code{(@var{proc}
386 @var{cont})} with it. The return value is the value returned by
387 @var{proc}, or when @code{(@var{cont} @var{value})} is later invoked,
388 the return is the @var{value} passed.
390 Normally @var{cont} should be called with one argument, but when the
391 location resumed is expecting multiple values (@pxref{Multiple
392 Values}) then they should be passed as multiple arguments, for
393 instance @code{(@var{cont} @var{x} @var{y} @var{z})}.
395 @var{cont} may only be used from the same side of a continuation
396 barrier as it was created (@pxref{Continuation Barriers}), and in a
397 multi-threaded program only from the thread in which it was created.
399 The call to @var{proc} is not part of the continuation captured, it runs
400 only when the continuation is created. Often a program will want to
401 store @var{cont} somewhere for later use; this can be done in
404 The @code{call} in the name @code{call-with-current-continuation}
405 refers to the way a call to @var{proc} gives the newly created
406 continuation. It's not related to the way a call is used later to
407 invoke that continuation.
409 @code{call/cc} is an alias for @code{call-with-current-continuation}.
410 This is in common use since the latter is rather long.
413 @deftypefn {C Function} SCM scm_make_continuation (int *first)
414 Capture the current continuation as described above. The return value
415 is the new continuation, and @var{*first} is set to 1.
417 When the continuation is invoked, @code{scm_make_continuation} will
418 return again, this time returning the value (or set of multiple
419 values) passed in that invocation, and with @var{*first} set to 0.
424 Here is a simple example,
428 (format #t "the return is ~a\n"
432 @result{} the return is 1
435 @result{} the return is 2
438 @code{call/cc} captures a continuation in which the value returned is
439 going to be displayed by @code{format}. The @code{lambda} stores this
440 in @code{kont} and gives an initial return @code{1} which is
441 displayed. The later invocation of @code{kont} resumes the captured
442 point, but this time returning @code{2}, which is displayed.
444 When Guile is run interactively, a call to @code{format} like this has
445 an implicit return back to the read-eval-print loop. @code{call/cc}
446 captures that like any other return, which is why interactively
447 @code{kont} will come back to read more input.
450 C programmers may note that @code{call/cc} is like @code{setjmp} in
451 the way it records at runtime a point in program execution. A call to
452 a continuation is like a @code{longjmp} in that it abandons the
453 present location and goes to the recorded one. Like @code{longjmp},
454 the value passed to the continuation is the value returned by
455 @code{call/cc} on resuming there. However @code{longjmp} can only go
456 up the program stack, but the continuation mechanism can go anywhere.
458 When a continuation is invoked, @code{call/cc} and subsequent code
459 effectively ``returns'' a second time. It can be confusing to imagine
460 a function returning more times than it was called. It may help
461 instead to think of it being stealthily re-entered and then program
462 flow going on as normal.
464 @code{dynamic-wind} (@pxref{Dynamic Wind}) can be used to ensure setup
465 and cleanup code is run when a program locus is resumed or abandoned
466 through the continuation mechanism. C code can use @dfn{frames}
470 Continuations are a powerful mechanism, and can be used to implement
471 almost any sort of control structure, such as loops, coroutines, or
474 However the implementation of continuations in Guile is not as
475 efficient as one might hope, because Guile is designed to cooperate
476 with programs written in other languages, such as C, which do not know
477 about continuations. Basically continuations are captured by a block
478 copy of the stack, and resumed by copying back.
480 For this reason, generally continuations should be used only when
481 there is no other simple way to achieve the desired result, or when
482 the elegance of the continuation mechanism outweighs the need for
485 Escapes upwards from loops or nested functions are generally best
486 handled with exceptions (@pxref{Exceptions}). Coroutines can be
487 efficiently implemented with cooperating threads (a thread holds a
488 full program stack but doesn't copy it around the way continuations
492 @node Multiple Values
493 @subsection Returning and Accepting Multiple Values
495 @cindex multiple values
498 Scheme allows a procedure to return more than one value to its caller.
499 This is quite different to other languages which only allow
500 single-value returns. Returning multiple values is different from
501 returning a list (or pair or vector) of values to the caller, because
502 conceptually not @emph{one} compound object is returned, but several
505 The primitive procedures for handling multiple values are @code{values}
506 and @code{call-with-values}. @code{values} is used for returning
507 multiple values from a procedure. This is done by placing a call to
508 @code{values} with zero or more arguments in tail position in a
509 procedure body. @code{call-with-values} combines a procedure returning
510 multiple values with a procedure which accepts these values as
514 @deffn {Scheme Procedure} values arg1 @dots{} argN
515 @deffnx {C Function} scm_values (args)
516 Delivers all of its arguments to its continuation. Except for
517 continuations created by the @code{call-with-values} procedure,
518 all continuations take exactly one value. The effect of
519 passing no value or more than one value to continuations that
520 were not created by @code{call-with-values} is unspecified.
522 For @code{scm_values}, @var{args} is a list of arguments and the
523 return is a multiple-values object which the caller can return. In
524 the current implementation that object shares structure with
525 @var{args}, so @var{args} should not be modified subsequently.
528 @rnindex call-with-values
529 @deffn {Scheme Procedure} call-with-values producer consumer
530 Calls its @var{producer} argument with no values and a
531 continuation that, when passed some values, calls the
532 @var{consumer} procedure with those values as arguments. The
533 continuation for the call to @var{consumer} is the continuation
534 of the call to @code{call-with-values}.
537 (call-with-values (lambda () (values 4 5))
543 (call-with-values * -)
548 In addition to the fundamental procedures described above, Guile has a
549 module which exports a syntax called @code{receive}, which is much more
550 convenient. If you want to use it in your programs, you have to load
551 the module @code{(ice-9 receive)} with the statement
554 (use-modules (ice-9 receive))
557 @deffn {library syntax} receive formals expr body @dots{}
558 Evaluate the expression @var{expr}, and bind the result values (zero or
559 more) to the formal arguments in the formal argument list @var{formals}.
560 @var{formals} must have the same syntax like the formal argument list
561 used in @code{lambda} (@pxref{Lambda}). After binding the variables,
562 the expressions in @var{body} @dots{} are evaluated in order.
567 @subsection Exceptions
568 @cindex error handling
569 @cindex exception handling
571 A common requirement in applications is to want to jump
572 @dfn{non-locally} from the depths of a computation back to, say, the
573 application's main processing loop. Usually, the place that is the
574 target of the jump is somewhere in the calling stack of procedures that
575 called the procedure that wants to jump back. For example, typical
576 logic for a key press driven application might look something like this:
580 read the next key press and call dispatch-key
583 lookup the key in a keymap and call an appropriate procedure,
587 interactively read the required file name, then call
591 check whether file exists; if not, jump back to main-loop
595 The jump back to @code{main-loop} could be achieved by returning through
596 the stack one procedure at a time, using the return value of each
597 procedure to indicate the error condition, but Guile (like most modern
598 programming languages) provides an additional mechanism called
599 @dfn{exception handling} that can be used to implement such jumps much
603 * Exception Terminology:: Different ways to say the same thing.
604 * Catch:: Setting up to catch exceptions.
605 * Throw:: Throwing an exception.
606 * Lazy Catch:: Catch without unwinding the stack.
607 * Exception Implementation:: How Guile implements exceptions.
611 @node Exception Terminology
612 @subsubsection Exception Terminology
614 There are several variations on the terminology for dealing with
615 non-local jumps. It is useful to be aware of them, and to realize
616 that they all refer to the same basic mechanism.
620 Actually making a non-local jump may be called @dfn{raising an
621 exception}, @dfn{raising a signal}, @dfn{throwing an exception} or
622 @dfn{doing a long jump}. When the jump indicates an error condition,
623 people may talk about @dfn{signalling}, @dfn{raising} or @dfn{throwing}
627 Handling the jump at its target may be referred to as @dfn{catching} or
628 @dfn{handling} the @dfn{exception}, @dfn{signal} or, where an error
629 condition is involved, @dfn{error}.
632 Where @dfn{signal} and @dfn{signalling} are used, special care is needed
633 to avoid the risk of confusion with POSIX signals.
635 This manual prefers to speak of throwing and catching exceptions, since
636 this terminology matches the corresponding Guile primitives.
640 @subsubsection Catching Exceptions
642 @code{catch} is used to set up a target for a possible non-local jump.
643 The arguments of a @code{catch} expression are a @dfn{key}, which
644 restricts the set of exceptions to which this @code{catch} applies, a
645 thunk that specifies the code to execute and a @dfn{handler} procedure
646 that says what to do if an exception is thrown while executing the code.
647 Note that if the execution thunk executes @dfn{normally}, which means
648 without throwing any exceptions, the handler procedure is not called at
651 When an exception is thrown using the @code{throw} function, the first
652 argument of the @code{throw} is a symbol that indicates the type of the
653 exception. For example, Guile throws an exception using the symbol
654 @code{numerical-overflow} to indicate numerical overflow errors such as
660 ABORT: (numerical-overflow)
663 The @var{key} argument in a @code{catch} expression corresponds to this
664 symbol. @var{key} may be a specific symbol, such as
665 @code{numerical-overflow}, in which case the @code{catch} applies
666 specifically to exceptions of that type; or it may be @code{#t}, which
667 means that the @code{catch} applies to all exceptions, irrespective of
670 The second argument of a @code{catch} expression should be a thunk
671 (i.e. a procedure that accepts no arguments) that specifies the normal
672 case code. The @code{catch} is active for the execution of this thunk,
673 including any code called directly or indirectly by the thunk's body.
674 Evaluation of the @code{catch} expression activates the catch and then
677 The third argument of a @code{catch} expression is a handler procedure.
678 If an exception is thrown, this procedure is called with exactly the
679 arguments specified by the @code{throw}. Therefore, the handler
680 procedure must be designed to accept a number of arguments that
681 corresponds to the number of arguments in all @code{throw} expressions
682 that can be caught by this @code{catch}.
684 @deffn {Scheme Procedure} catch key thunk handler
685 @deffnx {C Function} scm_catch (key, thunk, handler)
686 Invoke @var{thunk} in the dynamic context of @var{handler} for
687 exceptions matching @var{key}. If thunk throws to the symbol
688 @var{key}, then @var{handler} is invoked this way:
690 (handler key args ...)
693 @var{key} is a symbol or @code{#t}.
695 @var{thunk} takes no arguments. If @var{thunk} returns
696 normally, that is the return value of @code{catch}.
698 Handler is invoked outside the scope of its own @code{catch}.
699 If @var{handler} again throws to the same key, a new handler
700 from further up the call chain is invoked.
702 If the key is @code{#t}, then a throw to @emph{any} symbol will
703 match this call to @code{catch}.
706 If the handler procedure needs to match a variety of @code{throw}
707 expressions with varying numbers of arguments, you should write it like
716 The @var{key} argument is guaranteed always to be present, because a
717 @code{throw} without a @var{key} is not valid. The number and
718 interpretation of the @var{args} varies from one type of exception to
719 another, but should be specified by the documentation for each exception
722 Note that, once the handler procedure is invoked, the catch that led to
723 the handler procedure being called is no longer active. Therefore, if
724 the handler procedure itself throws an exception, that exception can
725 only be caught by another active catch higher up the call stack, if
729 @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)
730 The above @code{scm_catch} takes Scheme procedures as body and handler
731 arguments. @code{scm_internal_catch} is an equivalent taking C
734 @var{body} is called as @code{@var{body} (@var{body_data})} with a
735 catch on exceptions of the given @var{tag} type. If an exception is
736 caught, @var{handler} is called @code{@var{handler}
737 (@var{handler_data}, @var{key}, @var{args})}. @var{key} and
738 @var{args} are the @code{SCM} key and argument list from the
741 @tpindex scm_t_catch_body
742 @tpindex scm_t_catch_handler
743 @var{body} and @var{handler} should have the following prototypes.
744 @code{scm_t_catch_body} and @code{scm_t_catch_handler} are pointer
748 SCM body (void *data);
749 SCM handler (void *data, SCM key, SCM args);
752 The @var{body_data} and @var{handler_data} parameters are passed to
753 the respective calls so an application can communicate extra
754 information to those functions.
756 If the data consists of an @code{SCM} object, care should be taken
757 that it isn't garbage collected while still required. If the
758 @code{SCM} is a local C variable, one way to protect it is to pass a
759 pointer to that variable as the data parameter, since the C compiler
760 will then know the value must be held on the stack. Another way is to
761 use @code{scm_remember_upto_here_1} (@pxref{Remembering During
767 @subsubsection Throwing Exceptions
769 The @code{throw} primitive is used to throw an exception. One argument,
770 the @var{key}, is mandatory, and must be a symbol; it indicates the type
771 of exception that is being thrown. Following the @var{key},
772 @code{throw} accepts any number of additional arguments, whose meaning
773 depends on the exception type. The documentation for each possible type
774 of exception should specify the additional arguments that are expected
775 for that kind of exception.
777 @deffn {Scheme Procedure} throw key . args
778 @deffnx {C Function} scm_throw (key, args)
779 Invoke the catch form matching @var{key}, passing @var{args} to the
782 @var{key} is a symbol. It will match catches of the same symbol or of
785 If there is no handler at all, Guile prints an error and then exits.
788 When an exception is thrown, it will be caught by the innermost
789 @code{catch} expression that applies to the type of the thrown
790 exception; in other words, the innermost @code{catch} whose @var{key} is
791 @code{#t} or is the same symbol as that used in the @code{throw}
792 expression. Once Guile has identified the appropriate @code{catch}, it
793 handles the exception by applying that @code{catch} expression's handler
794 procedure to the arguments of the @code{throw}.
796 If there is no appropriate @code{catch} for a thrown exception, Guile
797 prints an error to the current error port indicating an uncaught
798 exception, and then exits. In practice, it is quite difficult to
799 observe this behaviour, because Guile when used interactively installs a
800 top level @code{catch} handler that will catch all exceptions and print
801 an appropriate error message @emph{without} exiting. For example, this
802 is what happens if you try to throw an unhandled exception in the
803 standard Guile REPL; note that Guile's command loop continues after the
807 guile> (throw 'badex)
808 <unnamed port>:3:1: In procedure gsubr-apply @dots{}
809 <unnamed port>:3:1: unhandled-exception: badex
814 The default uncaught exception behaviour can be observed by evaluating a
815 @code{throw} expression from the shell command line:
818 $ guile -c "(begin (throw 'badex) (display \"here\\n\"))"
819 guile: uncaught throw to badex: ()
824 That Guile exits immediately following the uncaught exception
825 is shown by the absence of any output from the @code{display}
826 expression, because Guile never gets to the point of evaluating that
831 @subsubsection Catch Without Unwinding
833 A @dfn{lazy catch} is used in the same way as a normal @code{catch},
834 with @var{key}, @var{thunk} and @var{handler} arguments specifying the
835 exception type, normal case code and handler procedure, but differs in
836 one important respect: the handler procedure is executed without
837 unwinding the call stack from the context of the @code{throw} expression
838 that caused the handler to be invoked.
840 @deffn {Scheme Procedure} lazy-catch key thunk handler
841 @deffnx {C Function} scm_lazy_catch (key, thunk, handler)
842 This behaves exactly like @code{catch}, except that it does
843 not unwind the stack before invoking @var{handler}.
844 The @var{handler} procedure is not allowed to return:
845 it must throw to another catch, or otherwise exit non-locally.
848 @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)
849 The above @code{scm_lazy_catch} takes Scheme procedures as body and
850 handler arguments. @code{scm_internal_lazy_catch} is an equivalent
851 taking C functions. See @code{scm_internal_catch} (@pxref{Catch}) for
852 a description of the parameters, the behaviour however of course
853 follows @code{lazy-catch}.
856 Typically, @var{handler} should save any desired state associated with
857 the stack at the point where the corresponding @code{throw} occurred,
858 and then throw an exception itself --- usually the same exception as the
859 one it caught. If @var{handler} is invoked and does @emph{not} throw an
860 exception, Guile itself throws an exception with key @code{misc-error}.
862 Not unwinding the stack means that throwing an exception that is caught
863 by a @code{lazy-catch} is @emph{almost} equivalent to calling the
864 @code{lazy-catch}'s handler inline instead of each @code{throw}, and
865 then omitting the surrounding @code{lazy-catch}. In other words,
869 (lambda () @dots{} (throw 'key args @dots{}) @dots{})
874 is @emph{almost} equivalent to
877 ((lambda () @dots{} (handler 'key args @dots{}) @dots{}))
881 But why only @emph{almost}? The difference is that with
882 @code{lazy-catch} (as with normal @code{catch}), the dynamic context is
883 unwound back to just outside the @code{lazy-catch} expression before
884 invoking the handler. (For an introduction to what is meant by dynamic
885 context, @xref{Dynamic Wind}.)
887 Then, when the handler @emph{itself} throws an exception, that exception
888 must be caught by some kind of @code{catch} (including perhaps another
889 @code{lazy-catch}) higher up the call stack.
891 The dynamic context also includes @code{with-fluids} blocks
892 (@pxref{Fluids and Dynamic States}),
893 so the effect of unwinding the dynamic context can also be seen in fluid
894 variable values. This is illustrated by the following code, in which
895 the normal case thunk uses @code{with-fluids} to temporarily change the
899 (define f (make-fluid))
900 (fluid-set! f "top level value")
902 (define (handler . args)
903 (cons (fluid-ref f) args))
907 (with-fluids ((f "local value"))
911 ("top level value" foo)
914 (with-fluids ((f "local value"))
921 In the @code{lazy-catch} version, the unwinding of dynamic context
922 restores @code{f} to its value outside the @code{with-fluids} block
923 before the handler is invoked, so the handler's @code{(fluid-ref f)}
924 returns the external value.
926 @code{lazy-catch} is useful because it permits the implementation of
927 debuggers and other reflective programming tools that need to access the
928 state of the call stack at the exact point where an exception or an
929 error is thrown. For an example of this, see REFFIXME:stack-catch.
932 @node Exception Implementation
933 @subsubsection How Guile Implements Exceptions
935 It is traditional in Scheme to implement exception systems using
936 @code{call-with-current-continuation}. Continuations
937 (@pxref{Continuations}) are such a powerful concept that any other
938 control mechanism --- including @code{catch} and @code{throw} --- can be
939 implemented in terms of them.
941 Guile does not implement @code{catch} and @code{throw} like this,
942 though. Why not? Because Guile is specifically designed to be easy to
943 integrate with applications written in C. In a mixed Scheme/C
944 environment, the concept of @dfn{continuation} must logically include
945 ``what happens next'' in the C parts of the application as well as the
946 Scheme parts, and it turns out that the only reasonable way of
947 implementing continuations like this is to save and restore the complete
950 So Guile's implementation of @code{call-with-current-continuation} is a
951 stack copying one. This allows it to interact well with ordinary C
952 code, but means that creating and calling a continuation is slowed down
953 by the time that it takes to copy the C stack.
955 The more targeted mechanism provided by @code{catch} and @code{throw}
956 does not need to save and restore the C stack because the @code{throw}
957 always jumps to a location higher up the stack of the code that executes
958 the @code{throw}. Therefore Guile implements the @code{catch} and
959 @code{throw} primitives independently of
960 @code{call-with-current-continuation}, in a way that takes advantage of
961 this @emph{upwards only} nature of exceptions.
964 @node Error Reporting
965 @subsection Procedures for Signaling Errors
967 Guile provides a set of convenience procedures for signaling error
968 conditions that are implemented on top of the exception primitives just
971 @deffn {Scheme Procedure} error msg args @dots{}
972 Raise an error with key @code{misc-error} and a message constructed by
973 displaying @var{msg} and writing @var{args}.
976 @deffn {Scheme Procedure} scm-error key subr message args data
977 @deffnx {C Function} scm_error_scm (key, subr, message, args, data)
978 Raise an error with key @var{key}. @var{subr} can be a string
979 naming the procedure associated with the error, or @code{#f}.
980 @var{message} is the error message string, possibly containing
981 @code{~S} and @code{~A} escapes. When an error is reported,
982 these are replaced by formatting the corresponding members of
983 @var{args}: @code{~A} (was @code{%s} in older versions of
984 Guile) formats using @code{display} and @code{~S} (was
985 @code{%S}) formats using @code{write}. @var{data} is a list or
986 @code{#f} depending on @var{key}: if @var{key} is
987 @code{system-error} then it should be a list containing the
988 Unix @code{errno} value; If @var{key} is @code{signal} then it
989 should be a list containing the Unix signal number; If
990 @var{key} is @code{out-of-range} or @code{wrong-type-arg},
991 it is a list containing the bad value; otherwise
992 it will usually be @code{#f}.
995 @deffn {Scheme Procedure} strerror err
996 @deffnx {C Function} scm_strerror (err)
997 Return the Unix error message corresponding to @var{err}, an integer
1000 When @code{setlocale} has been called (@pxref{Locales}), the message
1001 is in the language and charset of @code{LC_MESSAGES}. (This is done
1005 @c begin (scm-doc-string "boot-9.scm" "false-if-exception")
1006 @deffn syntax false-if-exception expr
1007 Returns the result of evaluating its argument; however
1008 if an exception occurs then @code{#f} is returned instead.
1014 @subsection Dynamic Wind
1016 @rnindex dynamic-wind
1017 @deffn {Scheme Procedure} dynamic-wind in_guard thunk out_guard
1018 @deffnx {C Function} scm_dynamic_wind (in_guard, thunk, out_guard)
1019 All three arguments must be 0-argument procedures.
1020 @var{in_guard} is called, then @var{thunk}, then
1023 If, any time during the execution of @var{thunk}, the
1024 dynamic extent of the @code{dynamic-wind} expression is escaped
1025 non-locally, @var{out_guard} is called. If the dynamic extent of
1026 the dynamic-wind is re-entered, @var{in_guard} is called. Thus
1027 @var{in_guard} and @var{out_guard} may be called any number of
1030 (define x 'normal-binding)
1032 (define a-cont (call-with-current-continuation
1038 (lambda () (set! x 'special-binding))
1042 (lambda () (display x) (newline)
1043 (call-with-current-continuation escape)
1044 (display x) (newline)
1049 (lambda () (set! x old-x)))))))
1056 @result{} normal-binding
1061 @result{} a-cont ;; the value of the (define a-cont...)
1063 @result{} normal-binding
1065 @result{} special-binding
1072 For Scheme code, the fundamental procedure to react to non-local entry
1073 and exits of dynamic contexts is @code{dynamic-wind}. C code could use
1074 @code{scm_internal_dynamic_wind}, but since C does not allow the
1075 convenient construction of anonymous procedures that close over lexical
1076 variables, this will be, well, inconvenient. Instead, C code can use
1079 Guile offers the functions @code{scm_frame_begin} and
1080 @code{scm_frame_end} to delimit a dynamic extent. Within this dynamic
1081 extent, which is called a @dfn{frame}, you can perform various
1082 @dfn{frame actions} that control what happens when the frame is entered
1083 or left. For example, you can register a cleanup routine with
1084 @code{scm_frame_unwind} that is executed when the frame is left. There are
1085 several other more specialized frame actions as well, for example to
1086 temporarily block the execution of asyncs or to temporarily change the
1087 current output port. They are described elsewhere in this manual.
1089 Here is an example that shows how to prevent memory leaks.
1093 /* Suppose there is a function called FOO in some library that you
1094 would like to make available to Scheme code (or to C code that
1095 follows the Scheme conventions).
1097 FOO takes two C strings and returns a new string. When an error has
1098 occurred in FOO, it returns NULL.
1101 char *foo (char *s1, char *s2);
1103 /* SCM_FOO interfaces the C function FOO to the Scheme way of life.
1104 It takes care to free up all temporary strings in the case of
1109 scm_foo (SCM s1, SCM s2)
1111 char *c_s1, *c_s2, *c_res;
1113 scm_frame_begin (0);
1115 c_s1 = scm_to_locale_string (s1);
1117 /* Call 'free (c_s1)' when the frame is left.
1119 scm_frame_unwind_handler (free, c_s1, SCM_F_WIND_EXPLICITLY);
1121 c_s2 = scm_to_locale_string (s2);
1123 /* Same as above, but more concisely.
1125 scm_frame_free (c_s2);
1127 c_res = foo (c_s1, c_s2);
1129 scm_memory_error ("foo");
1133 return scm_take_locale_string (res);
1137 @deftp {C Type} scm_t_frame_flags
1138 This is an enumeration of several flags that modify the behavior of
1139 @code{scm_begin_frame}. The flags are listed in the following table.
1142 @item SCM_F_FRAME_REWINDABLE
1143 The frame is @dfn{rewindable}. This means that it can be reentered
1144 non-locally (via the invokation of a continuation). The default is that
1145 a frame can not be reentered non-locally.
1150 @deftypefn {C Function} void scm_frame_begin (scm_t_frame_flags flags)
1151 The function @code{scm_begin_frame} starts a new frame and makes it the
1154 The @var{flags} argument determines the default behavior of the frame.
1155 For normal frames, use 0. This will result in a frame that can not be
1156 reentered with a captured continuation. When you are prepared to handle
1157 reentries, include @code{SCM_F_FRAME_REWINDABLE} in @var{flags}.
1159 Being prepared for reentry means that the effects of unwind handlers
1160 can be undone on reentry. In the example above, we want to prevent a
1161 memory leak on non-local exit and thus register an unwind handler that
1162 frees the memory. But once the memory is freed, we can not get it
1163 back on reentry. Thus reentry can not be allowed.
1165 The consequence is that continuations become less useful when
1166 non-reenterable frames are captured, but you don't need to worry about
1169 The frame is ended either implicitly when a non-local exit happens, or
1170 explicitly with @code{scm_end_frame}. You must make sure that a frame
1171 is indeed ended properly. If you fail to call @code{scm_end_frame}
1172 for each @code{scm_begin_frame}, the behavior is undefined.
1175 @deftypefn {C Function} void scm_frame_end ()
1176 End the current frame explicitly and make the previous frame current.
1179 @deftp {C Type} scm_t_wind_flags
1180 This is an enumeration of several flags that modify the behavior of
1181 @code{scm_on_unwind_handler} and @code{scm_on_rewind_handler}. The
1182 flags are listed in the following table.
1185 @item SCM_F_WIND_EXPLICITLY
1186 @vindex SCM_F_WIND_EXPLICITLY
1187 The registered action is also carried out when the frame is entered or
1192 @deftypefn {C Function} void scm_frame_unwind_handler (void (*func)(void *), void *data, scm_t_wind_flags flags)
1193 @deftypefnx {C Function} void scm_frame_unwind_handler_with_scm (void (*func)(SCM), SCM data, scm_t_wind_flags flags)
1194 Arranges for @var{func} to be called with @var{data} as its arguments
1195 when the current frame ends implicitly. If @var{flags} contains
1196 @code{SCM_F_WIND_EXPLICITLY}, @var{func} is also called when the frame
1197 ends explicitly with @code{scm_frame_end}.
1199 The function @code{scm_frame_unwind_handler_with_scm} takes care that
1200 @var{data} is protected from garbage collection.
1203 @deftypefn {C Function} void scm_frame_rewind_handler (void (*func)(void *), void *data, scm_t_wind_flags flags)
1204 @deftypefnx {C Function} void scm_frame_rewind_handler_with_scm (void (*func)(SCM), SCM data, scm_t_wind_flags flags)
1205 Arrange for @var{func} to be called with @var{data} as its argument when
1206 the current frame is restarted by rewinding the stack. When @var{flags}
1207 contains @code{SCM_F_WIND_EXPLICITLY}, @var{func} is called immediately
1210 The function @code{scm_frame_rewind_handler_with_scm} takes care that
1211 @var{data} is protected from garbage collection.
1215 @node Handling Errors
1216 @subsection How to Handle Errors
1218 Error handling is based on @code{catch} and @code{throw}. Errors are
1219 always thrown with a @var{key} and four arguments:
1223 @var{key}: a symbol which indicates the type of error. The symbols used
1224 by libguile are listed below.
1227 @var{subr}: the name of the procedure from which the error is thrown, or
1231 @var{message}: a string (possibly language and system dependent)
1232 describing the error. The tokens @code{~A} and @code{~S} can be
1233 embedded within the message: they will be replaced with members of the
1234 @var{args} list when the message is printed. @code{~A} indicates an
1235 argument printed using @code{display}, while @code{~S} indicates an
1236 argument printed using @code{write}. @var{message} can also be
1237 @code{#f}, to allow it to be derived from the @var{key} by the error
1238 handler (may be useful if the @var{key} is to be thrown from both C and
1242 @var{args}: a list of arguments to be used to expand @code{~A} and
1243 @code{~S} tokens in @var{message}. Can also be @code{#f} if no
1244 arguments are required.
1247 @var{rest}: a list of any additional objects required. e.g., when the
1248 key is @code{'system-error}, this contains the C errno value. Can also
1249 be @code{#f} if no additional objects are required.
1252 In addition to @code{catch} and @code{throw}, the following Scheme
1253 facilities are available:
1255 @deffn {Scheme Procedure} display-error stack port subr message args rest
1256 @deffnx {C Function} scm_display_error (stack, port, subr, message, args, rest)
1257 Display an error message to the output port @var{port}.
1258 @var{stack} is the saved stack for the error, @var{subr} is
1259 the name of the procedure in which the error occurred and
1260 @var{message} is the actual error message, which may contain
1261 formatting instructions. These will format the arguments in
1262 the list @var{args} accordingly. @var{rest} is currently
1266 The following are the error keys defined by libguile and the situations
1267 in which they are used:
1271 @cindex @code{error-signal}
1272 @code{error-signal}: thrown after receiving an unhandled fatal signal
1273 such as SIGSEGV, SIGBUS, SIGFPE etc. The @var{rest} argument in the throw
1274 contains the coded signal number (at present this is not the same as the
1275 usual Unix signal number).
1278 @cindex @code{system-error}
1279 @code{system-error}: thrown after the operating system indicates an
1280 error condition. The @var{rest} argument in the throw contains the
1284 @cindex @code{numerical-overflow}
1285 @code{numerical-overflow}: numerical overflow.
1288 @cindex @code{out-of-range}
1289 @code{out-of-range}: the arguments to a procedure do not fall within the
1293 @cindex @code{wrong-type-arg}
1294 @code{wrong-type-arg}: an argument to a procedure has the wrong type.
1297 @cindex @code{wrong-number-of-args}
1298 @code{wrong-number-of-args}: a procedure was called with the wrong number
1302 @cindex @code{memory-allocation-error}
1303 @code{memory-allocation-error}: memory allocation error.
1306 @cindex @code{stack-overflow}
1307 @code{stack-overflow}: stack overflow error.
1310 @cindex @code{regular-expression-syntax}
1311 @code{regular-expression-syntax}: errors generated by the regular
1315 @cindex @code{misc-error}
1316 @code{misc-error}: other errors.
1320 @subsubsection C Support
1322 In the following C functions, @var{SUBR} and @var{MESSAGE} parameters
1323 can be @code{NULL} to give the effect of @code{#f} described above.
1325 @deftypefn {C Function} SCM scm_error (SCM @var{key}, char *@var{subr}, char *@var{message}, SCM @var{args}, SCM @var{rest})
1326 Throw an error, as per @code{scm-error} above.
1329 @deftypefn {C Function} void scm_syserror (char *@var{subr})
1330 @deftypefnx {C Function} void scm_syserror_msg (char *@var{subr}, char *@var{message}, SCM @var{args})
1331 Throw an error with key @code{system-error} and supply @code{errno} in
1332 the @var{rest} argument. For @code{scm_syserror} the message is
1333 generated using @code{strerror}.
1335 Care should be taken that any code in between the failing operation
1336 and the call to these routines doesn't change @code{errno}.
1339 @deftypefn {C Function} void scm_num_overflow (char *@var{subr})
1340 @deftypefnx {C Function} void scm_out_of_range (char *@var{subr}, SCM @var{bad_value})
1341 @deftypefnx {C Function} void scm_wrong_num_args (SCM @var{proc})
1342 @deftypefnx {C Function} void scm_wrong_type_arg (char *@var{subr}, int @var{argnum}, SCM @var{bad_value})
1343 @deftypefnx {C Function} void scm_memory_error (char *@var{subr})
1344 Throw an error with the various keys described above.
1346 For @code{scm_wrong_num_args}, @var{proc} should be a Scheme symbol
1347 which is the name of the procedure incorrectly invoked.
1352 @c TeX-master: "guile.texi"