2 @node Control Mechanisms
3 @chapter Controlling the Flow of Program Execution
6 * begin:: Evaluating a sequence of expressions.
7 * if cond case:: Simple conditional evaluation.
8 * and or:: Conditional evaluation of a sequence.
9 * while do:: Iteration mechanisms.
10 * Continuations:: Continuations.
11 * Multiple Values:: Returning and accepting multiple values.
12 * Exceptions:: Throwing and catching exceptions.
13 * Error Reporting:: Procedures for signaling errors.
14 * Dynamic Wind:: Guarding against non-local entrance/exit.
15 * Handling Errors:: How to handle errors in C code.
20 @section Evaluating a Sequence of Expressions
22 @c FIXME::martin: Review me!
24 @c FIXME::martin: Maybe add examples?
28 @cindex expression sequencing
30 @code{begin} is used for grouping several expression together so that
31 they syntactically are treated as if they were one expression. This is
32 particularly important when syntactic expressions are used which only
33 allow one expression, but the programmer wants to use more than one
34 expression in that place. As an example, consider the conditional
39 (begin (display "greater") (newline)))
42 If the two calls to @code{display} and @code{newline} were not embedded
43 in a @code{begin}-statement, the call to @code{newline} would get
44 misinterpreted as the else-branch of the @code{if}-expression.
46 @deffn syntax begin expr1 expr2 @dots{}
47 The expression(s) are evaluated in left-to-right order and the value
48 of the last expression is returned as the value of the
49 @code{begin}-expression. This expression type is used when the
50 expressions before the last one are evaluated for their side effects.
54 @section Simple Conditional Evaluation
56 @c FIXME::martin: Review me!
58 @c FIXME::martin: Maybe add examples?
60 @cindex conditional evaluation
65 Guile provides three syntactic constructs for conditional evaluation.
66 @code{if} is the normal if-then-else expression (with an optional else
67 branch), @code{cond} is a conditional expression with multiple branches
68 and @code{case} branches if an expression has one of a set of constant
71 @deffn syntax if test consequent [alternate]
72 All arguments may be arbitrary expressions. First, @var{test} is
73 evaluated. If it returns a true value, the expression @var{consequent}
74 is evaluated and @var{alternate} is ignored. If @var{test} evaluates to
75 @code{#f}, @var{alternate} is evaluated instead. The value of the
76 evaluated branch (@var{consequent} or @var{alternate}) is returned as
77 the value of the @code{if} expression.
79 When @var{alternate} is omitted and the @var{test} evaluates to
80 @code{#f}, the value of the expression is not specified.
83 @deffn syntax cond clause1 clause2 @dots{}
84 Each @code{cond}-clause must look like this:
87 (@var{test} @var{expression} @dots{})
90 where @var{test} and @var{expression} are arbitrary expression, or like
94 (@var{test} => @var{expression}
97 where @var{expression} must evaluate to a procedure.
99 The @var{test}s of the clauses are evaluated in order and as soon as one
100 of them evaluates to a true values, the corresponding @var{expression}s
101 are evaluated in order and the last value is returned as the value of
102 the @code{cond}-expression. For the @code{=>} clause type,
103 @var{expression} is evaluated and the resulting procedure is applied to
104 the value of @var{test}. The result of this procedure application is
105 then the result of the @code{cond}-expression.
107 The @var{test} of the last @var{clause} may be the keyword @code{else}.
108 Then, if none of the preceding @var{test}s is true, the @var{expression}s following the @code{else} are evaluated to produce the result of the @code{cond}-expression.
111 @deffn syntax case key clause1 clause2 @dots{}
112 @var{key} may be any expression, the @var{clause}s must have the form
115 ((@var{datum1} @dots{}) @var{expr1} @var{expr2} @dots{})
118 and the last @var{clause} may have the form
121 (else @var{expr1} @var{expr2} @dots{})
124 All @var{datum}s must be distinct. First, @var{key} is evaluated. The
125 the result of this evaluation is compared against all @var{datum}s using
126 @code{eqv?}. When this comparison succeeds, the expression(s) following
127 the @var{datum} are evaluated from left to right, returning the value of
128 the last expression as the result of the @code{case} expression.
130 If the @var{key} matches no @var{datum} and there is an
131 @code{else}-clause, the expressions following the @code{else} are
132 evaluated. If there is no such clause, the result of the expression is
138 @section Conditional Evaluation of a Sequence of Expressions
140 @c FIXME::martin: Review me!
142 @c FIXME::martin: Maybe add examples?
144 @code{and} and @code{or} evaluate all their arguments, similar to
145 @code{begin}, but evaluation stops as soon as one of the expressions
146 evaluates to false or true, respectively.
148 @deffn syntax and expr @dots{}
149 Evaluate the @var{expr}s from left to right and stop evaluation as soon
150 as one expression evaluates to @code{#f}; the remaining expressions are
151 not evaluated. The value of the last evaluated expression is returned.
152 If no expression evaluates to @code{#f}, the value of the last
153 expression is returned.
155 If used without expressions, @code{#t} is returned.
158 @deffn syntax or expr @dots{}
159 Evaluate the @var{expr}s from left to right and stop evaluation as soon
160 as one expression evaluates to a true value (that is, a value different
161 from @code{#f}); the remaining expressions are not evaluated. The value
162 of the last evaluated expression is returned. If all expressions
163 evaluate to @code{#f}, @code{#f} is returned.
165 If used without expressions, @code{#f} is returned.
170 @section Iteration mechanisms
172 @c FIXME::martin: Review me!
174 @c FIXME::martin: Maybe add examples?
180 Scheme has only few iteration mechanisms, mainly because iteration in
181 Scheme programs is normally expressed using recursion. Nevertheless,
182 R5RS defines a construct for programming loops, calling @code{do}. In
183 addition, Guile has an explicit looping syntax called @code{while}.
185 @deffn syntax do ((variable1 init1 step1) @dots{}) (test expr @dots{}) command @dots{}
186 The @var{init} expressions are evaluated and the @var{variables} are
187 bound to their values. Then looping starts with testing the @var{test}
188 expression. If @var{test} evaluates to a true value, the @var{expr}
189 following the @var{test} are evaluated and the value of the last
190 @var{expr} is returned as the value of the @code{do} expression. If
191 @var{test} evaluates to false, the @var{command}s are evaluated in
192 order, the @var{step}s are evaluated and stored into the @var{variables}
193 and the next iteration starts.
195 Any of the @var{step} expressions may be omitted, so that the
196 corresponding variable is not changed during looping.
199 @deffn syntax while cond body @dots{}
200 Evaluate all expressions in @var{body} in order, as long as @var{cond}
201 evaluates to a true value. The @var{cond} expression is tested before
202 every iteration, so that the body is not evaluated at all if @var{cond}
203 is @code{#f} right from the start.
207 Another very common way of expressing iteration in Scheme programs is
208 the use of the so-called @dfn{named let}.
210 Named let is a variant of @code{let} which creates a procedure and calls
211 it in one step. Because of the newly created procedure, named let is
212 more powerful than @code{do}--it can be used for iteration, but also
213 for arbitrary recursion.
215 @deffn syntax let variable bindings body
216 For the definition of @var{bindings} see the documentation about
217 @code{let} (@pxref{Local Bindings}).
219 Named @code{let} works as follows:
223 A new procedure which accepts as many arguments as are in @var{bindings}
224 is created and bound locally (using @code{let}) to @var{variable}. The
225 new procedure's formal argument names are the name of the
229 The @var{body} expressions are inserted into the newly created procedure.
232 The procedure is called with the @var{init} expressions as the formal
236 The next example implements a loop which iterates (by recursion) 1000
251 @section Continuations
254 @cindex call-with-current-continuation
255 The ability to explicitly capture continuations using
256 @code{call-with-current-continuation} (also often called @code{call/cc}
257 for short), and to invoke such continuations later any number of times,
258 and from any other point in a program, provides maybe the most powerful
259 control structure known. All other control structures, such as loops
260 and coroutines, can be emulated using continuations.
262 @c NJFIXME - need a little something here about what continuations are
263 @c and what they do for you.
265 The implementation of continuations in Guile is not as efficient as one
266 might hope, because it is constrained by the fact that Guile is designed
267 to cooperate with programs written in other languages, such as C, which
268 do not know about continuations. So continuations should be used when
269 there is no other simple way of achieving the desired behaviour, or
270 where the advantages of the elegant continuation mechanism outweigh the
271 need for optimum performance. If you find yourself using @code{call/cc}
272 for escape procedures and your program is running too slow, you might
273 want to use exceptions (@pxref{Exceptions}) instead.
275 @rnindex call-with-current-continuation
276 @deffn {Scheme Procedure} call-with-current-continuation proc
277 Capture the current continuation and call @var{proc} with the captured
278 continuation as the single argument. This continuation can then be
279 called with arbitrarily many arguments. Such a call will work like a
280 goto to the invocation location of
281 @code{call-with-current-continuation}, passing the arguments in a way
282 that they are returned by the call to
283 @code{call-with-current-continuation}. Since it is legal to store the
284 captured continuation in a variable or to pass it to other procedures,
285 it is possible that a procedure returns more than once, even if it is
286 called only one time. This can be confusing at times.
289 @c FIXME::martin: Better example needed.
292 (call-with-current-continuation
305 @node Multiple Values
306 @section Returning and Accepting Multiple Values
308 @c FIXME::martin: Review me!
309 @cindex multiple values
312 Scheme allows a procedure to return more than one value to its caller.
313 This is quite different to other languages which only allow
314 single-value returns. Returning multiple values is different from
315 returning a list (or pair or vector) of values to the caller, because
316 conceptually not @emph{one} compound object is returned, but several
319 The primitive procedures for handling multiple values are @code{values}
320 and @code{call-with-values}. @code{values} is used for returning
321 multiple values from a procedure. This is done by placing a call to
322 @code{values} with zero or more arguments in tail position in a
323 procedure body. @code{call-with-values} combines a procedure returning
324 multiple values with a procedure which accepts these values as
328 @deffn {Scheme Procedure} values . args
329 @deffnx {C Function} scm_values (args)
330 Delivers all of its arguments to its continuation. Except for
331 continuations created by the @code{call-with-values} procedure,
332 all continuations take exactly one value. The effect of
333 passing no value or more than one value to continuations that
334 were not created by @code{call-with-values} is unspecified.
337 @rnindex call-with-values
338 @deffn {Scheme Procedure} call-with-values producer consumer
339 Calls its @var{producer} argument with no values and a
340 continuation that, when passed some values, calls the
341 @var{consumer} procedure with those values as arguments. The
342 continuation for the call to @var{consumer} is the continuation
343 of the call to @code{call-with-values}.
346 (call-with-values (lambda () (values 4 5))
352 (call-with-values * -) ==> -1
356 In addition to the fundamental procedures described above, Guile has a
357 module which exports a syntax called @code{receive}, which is much more
358 convenient. If you want to use it in your programs, you have to load
359 the module @code{(ice-9 receive)} with the statement
362 (use-modules (ice-9 receive))
365 @deffn {library syntax} receive formals expr body @dots{}
366 Evaluate the expression @var{expr}, and bind the result values (zero or
367 more) to the formal arguments in the formal argument list @var{formals}.
368 @var{formals} must have the same syntax like the formal argument list
369 used in @code{lambda} (@pxref{Lambda}). After binding the variables,
370 the expressions in @var{body} @dots{} are evaluated in order.
376 @cindex error handling
377 @cindex exception handling
379 A common requirement in applications is to want to jump
380 @dfn{non-locally} from the depths of a computation back to, say, the
381 application's main processing loop. Usually, the place that is the
382 target of the jump is somewhere in the calling stack of procedures that
383 called the procedure that wants to jump back. For example, typical
384 logic for a key press driven application might look something like this:
388 read the next key press and call dispatch-key
391 lookup the key in a keymap and call an appropriate procedure,
395 interactively read the required file name, then call
399 check whether file exists; if not, jump back to main-loop
403 The jump back to @code{main-loop} could be achieved by returning through
404 the stack one procedure at a time, using the return value of each
405 procedure to indicate the error condition, but Guile (like most modern
406 programming languages) provides an additional mechanism called
407 @dfn{exception handling} that can be used to implement such jumps much
411 * Exception Terminology:: Different ways to say the same thing.
412 * Catch:: Setting up to catch exceptions.
413 * Throw:: Throwing an exception.
414 * Lazy Catch:: Catch without unwinding the stack.
415 * Exception Implementation:: How Guile implements exceptions.
419 @node Exception Terminology
420 @subsection Exception Terminology
422 There are several variations on the terminology for dealing with
423 non-local jumps. It is useful to be aware of them, and to realize
424 that they all refer to the same basic mechanism.
428 Actually making a non-local jump may be called @dfn{raising an
429 exception}, @dfn{raising a signal}, @dfn{throwing an exception} or
430 @dfn{doing a long jump}. When the jump indicates an error condition,
431 people may talk about @dfn{signalling}, @dfn{raising} or @dfn{throwing}
435 Handling the jump at its target may be referred to as @dfn{catching} or
436 @dfn{handling} the @dfn{exception}, @dfn{signal} or, where an error
437 condition is involved, @dfn{error}.
440 Where @dfn{signal} and @dfn{signalling} are used, special care is needed
441 to avoid the risk of confusion with POSIX signals. (Especially
442 considering that Guile handles POSIX signals by throwing a corresponding
443 kind of exception: REFFIXME.)
445 This manual prefers to speak of throwing and catching exceptions, since
446 this terminology matches the corresponding Guile primitives.
450 @subsection Catching Exceptions
452 @code{catch} is used to set up a target for a possible non-local jump.
453 The arguments of a @code{catch} expression are a @dfn{key}, which
454 restricts the set of exceptions to which this @code{catch} applies, a
455 thunk that specifies the @dfn{normal case} code --- i.e. what should
456 happen if no exceptions are thrown --- and a @dfn{handler} procedure
457 that says what to do if an exception is thrown. Note that if the
458 @dfn{normal case} thunk executes @dfn{normally}, which means without
459 throwing any exceptions, the handler procedure is not executed at all.
461 When an exception is thrown using the @code{throw} primitive, the first
462 argument of the @code{throw} is a symbol that indicates the type of the
463 exception. For example, Guile throws an exception using the symbol
464 @code{numerical-overflow} to indicate numerical overflow errors such as
470 ABORT: (numerical-overflow)
473 The @var{key} argument in a @code{catch} expression corresponds to this
474 symbol. @var{key} may be a specific symbol, such as
475 @code{numerical-overflow}, in which case the @code{catch} applies
476 specifically to exceptions of that type; or it may be @code{#t}, which
477 means that the @code{catch} applies to all exceptions, irrespective of
480 The second argument of a @code{catch} expression should be a thunk
481 (i.e. a procedure that accepts no arguments) that specifies the normal
482 case code. The @code{catch} is active for the execution of this thunk,
483 including any code called directly or indirectly by the thunk's body.
484 Evaluation of the @code{catch} expression activates the catch and then
487 The third argument of a @code{catch} expression is a handler procedure.
488 If an exception is thrown, this procedure is called with exactly the
489 arguments specified by the @code{throw}. Therefore, the handler
490 procedure must be designed to accept a number of arguments that
491 corresponds to the number of arguments in all @code{throw} expressions
492 that can be caught by this @code{catch}.
494 @deffn {Scheme Procedure} catch key thunk handler
495 @deffnx {C Function} scm_catch (key, thunk, handler)
496 Invoke @var{thunk} in the dynamic context of @var{handler} for
497 exceptions matching @var{key}. If thunk throws to the symbol
498 @var{key}, then @var{handler} is invoked this way:
500 (handler key args ...)
503 @var{key} is a symbol or @code{#t}.
505 @var{thunk} takes no arguments. If @var{thunk} returns
506 normally, that is the return value of @code{catch}.
508 Handler is invoked outside the scope of its own @code{catch}.
509 If @var{handler} again throws to the same key, a new handler
510 from further up the call chain is invoked.
512 If the key is @code{#t}, then a throw to @emph{any} symbol will
513 match this call to @code{catch}.
516 If the handler procedure needs to match a variety of @code{throw}
517 expressions with varying numbers of arguments, you should write it like
526 The @var{key} argument is guaranteed always to be present, because a
527 @code{throw} without a @var{key} is not valid. The number and
528 interpretation of the @var{args} varies from one type of exception to
529 another, but should be specified by the documentation for each exception
532 Note that, once the handler procedure is invoked, the catch that led to
533 the handler procedure being called is no longer active. Therefore, if
534 the handler procedure itself throws an exception, that exception can
535 only be caught by another active catch higher up the call stack, if
540 @subsection Throwing Exceptions
542 The @code{throw} primitive is used to throw an exception. One argument,
543 the @var{key}, is mandatory, and must be a symbol; it indicates the type
544 of exception that is being thrown. Following the @var{key},
545 @code{throw} accepts any number of additional arguments, whose meaning
546 depends on the exception type. The documentation for each possible type
547 of exception should specify the additional arguments that are expected
548 for that kind of exception.
550 @deffn {Scheme Procedure} throw key . args
551 @deffnx {C Function} scm_throw (key, args)
552 Invoke the catch form matching @var{key}, passing @var{args} to the
555 @var{key} is a symbol. It will match catches of the same symbol or of
558 If there is no handler at all, Guile prints an error and then exits.
561 When an exception is thrown, it will be caught by the innermost
562 @code{catch} expression that applies to the type of the thrown
563 exception; in other words, the innermost @code{catch} whose @var{key} is
564 @code{#t} or is the same symbol as that used in the @code{throw}
565 expression. Once Guile has identified the appropriate @code{catch}, it
566 handles the exception by applying that @code{catch} expression's handler
567 procedure to the arguments of the @code{throw}.
569 If there is no appropriate @code{catch} for a thrown exception, Guile
570 prints an error to the current error port indicating an uncaught
571 exception, and then exits. In practice, it is quite difficult to
572 observe this behaviour, because Guile when used interactively installs a
573 top level @code{catch} handler that will catch all exceptions and print
574 an appropriate error message @emph{without} exiting. For example, this
575 is what happens if you try to throw an unhandled exception in the
576 standard Guile REPL; note that Guile's command loop continues after the
580 guile> (throw 'badex)
581 <unnamed port>:3:1: In procedure gsubr-apply @dots{}
582 <unnamed port>:3:1: unhandled-exception: badex
587 The default uncaught exception behaviour can be observed by evaluating a
588 @code{throw} expression from the shell command line:
591 $ guile -c "(begin (throw 'badex) (display \"here\\n\"))"
592 guile: uncaught throw to badex: ()
597 That Guile exits immediately following the uncaught exception
598 is shown by the absence of any output from the @code{display}
599 expression, because Guile never gets to the point of evaluating that
604 @subsection Catch Without Unwinding
606 A @dfn{lazy catch} is used in the same way as a normal @code{catch},
607 with @var{key}, @var{thunk} and @var{handler} arguments specifying the
608 exception type, normal case code and handler procedure, but differs in
609 one important respect: the handler procedure is executed without
610 unwinding the call stack from the context of the @code{throw} expression
611 that caused the handler to be invoked.
613 @deffn {Scheme Procedure} lazy-catch key thunk handler
614 @deffnx {C Function} scm_lazy_catch (key, thunk, handler)
615 This behaves exactly like @code{catch}, except that it does
616 not unwind the stack before invoking @var{handler}.
617 The @var{handler} procedure is not allowed to return:
618 it must throw to another catch, or otherwise exit non-locally.
621 Typically, @var{handler} should save any desired state associated with
622 the stack at the point where the corresponding @code{throw} occurred,
623 and then throw an exception itself --- usually the same exception as the
624 one it caught. If @var{handler} is invoked and does @emph{not} throw an
625 exception, Guile itself throws an exception with key @code{misc-error}.
627 Not unwinding the stack means that throwing an exception that is caught
628 by a @code{lazy-catch} is @emph{almost} equivalent to calling the
629 @code{lazy-catch}'s handler inline instead of each @code{throw}, and
630 then omitting the surrounding @code{lazy-catch}. In other words,
634 (lambda () @dots{} (throw 'key args @dots{}) @dots{})
639 is @emph{almost} equivalent to
642 ((lambda () @dots{} (handler 'key args @dots{}) @dots{}))
646 But why only @emph{almost}? The difference is that with
647 @code{lazy-catch} (as with normal @code{catch}), the dynamic context is
648 unwound back to just outside the @code{lazy-catch} expression before
649 invoking the handler. (For an introduction to what is meant by dynamic
650 context, @xref{Dynamic Wind}.)
652 Then, when the handler @emph{itself} throws an exception, that exception
653 must be caught by some kind of @code{catch} (including perhaps another
654 @code{lazy-catch}) higher up the call stack.
656 The dynamic context also includes @code{with-fluids} blocks (REFFIXME),
657 so the effect of unwinding the dynamic context can also be seen in fluid
658 variable values. This is illustrated by the following code, in which
659 the normal case thunk uses @code{with-fluids} to temporarily change the
663 (define f (make-fluid))
664 (fluid-set! f "top level value")
666 (define (handler . args)
667 (cons (fluid-ref f) args))
671 (with-fluids ((f "local value"))
675 ("top level value" foo)
678 (with-fluids ((f "local value"))
685 In the @code{lazy-catch} version, the unwinding of dynamic context
686 restores @code{f} to its value outside the @code{with-fluids} block
687 before the handler is invoked, so the handler's @code{(fluid-ref f)}
688 returns the external value.
690 @code{lazy-catch} is useful because it permits the implementation of
691 debuggers and other reflective programming tools that need to access the
692 state of the call stack at the exact point where an exception or an
693 error is thrown. For an example of this, see REFFIXME:stack-catch.
696 @node Exception Implementation
697 @subsection How Guile Implements Exceptions
699 It is traditional in Scheme to implement exception systems using
700 @code{call-with-current-continuation}. Continuations
701 (@pxref{Continuations}) are such a powerful concept that any other
702 control mechanism --- including @code{catch} and @code{throw} --- can be
703 implemented in terms of them.
705 Guile does not implement @code{catch} and @code{throw} like this,
706 though. Why not? Because Guile is specifically designed to be easy to
707 integrate with applications written in C. In a mixed Scheme/C
708 environment, the concept of @dfn{continuation} must logically include
709 ``what happens next'' in the C parts of the application as well as the
710 Scheme parts, and it turns out that the only reasonable way of
711 implementing continuations like this is to save and restore the complete
714 So Guile's implementation of @code{call-with-current-continuation} is a
715 stack copying one. This allows it to interact well with ordinary C
716 code, but means that creating and calling a continuation is slowed down
717 by the time that it takes to copy the C stack.
719 The more targeted mechanism provided by @code{catch} and @code{throw}
720 does not need to save and restore the C stack because the @code{throw}
721 always jumps to a location higher up the stack of the code that executes
722 the @code{throw}. Therefore Guile implements the @code{catch} and
723 @code{throw} primitives independently of
724 @code{call-with-current-continuation}, in a way that takes advantage of
725 this @emph{upwards only} nature of exceptions.
728 @node Error Reporting
729 @section Procedures for Signaling Errors
731 Guile provides a set of convenience procedures for signaling error
732 conditions that are implemented on top of the exception primitives just
735 @deffn {Scheme Procedure} error msg args @dots{}
736 Raise an error with key @code{misc-error} and a message constructed by
737 displaying @var{msg} and writing @var{args}.
740 @deffn {Scheme Procedure} scm-error key subr message args data
741 @deffnx {C Function} scm_error_scm (key, subr, message, args, data)
742 Raise an error with key @var{key}. @var{subr} can be a string
743 naming the procedure associated with the error, or @code{#f}.
744 @var{message} is the error message string, possibly containing
745 @code{~S} and @code{~A} escapes. When an error is reported,
746 these are replaced by formatting the corresponding members of
747 @var{args}: @code{~A} (was @code{%s} in older versions of
748 Guile) formats using @code{display} and @code{~S} (was
749 @code{%S}) formats using @code{write}. @var{data} is a list or
750 @code{#f} depending on @var{key}: if @var{key} is
751 @code{system-error} then it should be a list containing the
752 Unix @code{errno} value; If @var{key} is @code{signal} then it
753 should be a list containing the Unix signal number; otherwise
754 it will usually be @code{#f}.
757 @deffn {Scheme Procedure} strerror err
758 @deffnx {C Function} scm_strerror (err)
759 Return the Unix error message corresponding to @var{err}, which
760 must be an integer value.
763 @c begin (scm-doc-string "boot-9.scm" "false-if-exception")
764 @deffn syntax false-if-exception expr
765 Returns the result of evaluating its argument; however
766 if an exception occurs then @code{#f} is returned instead.
772 @section Dynamic Wind
774 [FIXME: this is pasted in from Tom Lord's original guile.texi and should
777 @rnindex dynamic-wind
778 @deffn {Scheme Procedure} dynamic-wind in_guard thunk out_guard
779 @deffnx {C Function} scm_dynamic_wind (in_guard, thunk, out_guard)
780 All three arguments must be 0-argument procedures.
781 @var{in_guard} is called, then @var{thunk}, then
784 If, any time during the execution of @var{thunk}, the
785 continuation of the @code{dynamic_wind} expression is escaped
786 non-locally, @var{out_guard} is called. If the continuation of
787 the dynamic-wind is re-entered, @var{in_guard} is called. Thus
788 @var{in_guard} and @var{out_guard} may be called any number of
791 (define x 'normal-binding)
793 (define a-cont (call-with-current-continuation
799 (lambda () (set! x 'special-binding))
803 (lambda () (display x) (newline)
804 (call-with-current-continuation escape)
805 (display x) (newline)
810 (lambda () (set! x old-x)))))))
817 @result{} normal-binding
822 @result{} a-cont ;; the value of the (define a-cont...)
824 @result{} normal-binding
826 @result{} special-binding
831 @node Handling Errors
832 @section How to Handle Errors in C Code
834 Error handling is based on @code{catch} and @code{throw}. Errors are
835 always thrown with a @var{key} and four arguments:
839 @var{key}: a symbol which indicates the type of error. The symbols used
840 by libguile are listed below.
843 @var{subr}: the name of the procedure from which the error is thrown, or
847 @var{message}: a string (possibly language and system dependent)
848 describing the error. The tokens @code{~A} and @code{~S} can be
849 embedded within the message: they will be replaced with members of the
850 @var{args} list when the message is printed. @code{~A} indicates an
851 argument printed using @code{display}, while @code{~S} indicates an
852 argument printed using @code{write}. @var{message} can also be
853 @code{#f}, to allow it to be derived from the @var{key} by the error
854 handler (may be useful if the @var{key} is to be thrown from both C and
858 @var{args}: a list of arguments to be used to expand @code{~A} and
859 @code{~S} tokens in @var{message}. Can also be @code{#f} if no
860 arguments are required.
863 @var{rest}: a list of any additional objects required. e.g., when the
864 key is @code{'system-error}, this contains the C errno value. Can also
865 be @code{#f} if no additional objects are required.
868 In addition to @code{catch} and @code{throw}, the following Scheme
869 facilities are available:
871 @deffn {Scheme Procedure} scm-error key subr message args rest
872 Throw an error, with arguments
876 @deffn {Scheme Procedure} error msg arg @dots{}
877 Throw an error using the key @code{'misc-error}. The error
878 message is created by displaying @var{msg} and writing the @var{args}.
881 @deffn {Scheme Procedure} display-error stack port subr message args rest
882 @deffnx {C Function} scm_display_error (stack, port, subr, message, args, rest)
883 Display an error message to the output port @var{port}.
884 @var{stack} is the saved stack for the error, @var{subr} is
885 the name of the procedure in which the error occurred and
886 @var{message} is the actual error message, which may contain
887 formatting instructions. These will format the arguments in
888 the list @var{args} accordingly. @var{rest} is currently
892 The following are the error keys defined by libguile and the situations
893 in which they are used:
897 @code{error-signal}: thrown after receiving an unhandled fatal signal
898 such as SIGSEGV, SIGBUS, SIGFPE etc. The @var{rest} argument in the throw
899 contains the coded signal number (at present this is not the same as the
900 usual Unix signal number).
903 @code{system-error}: thrown after the operating system indicates an
904 error condition. The @var{rest} argument in the throw contains the
908 @code{numerical-overflow}: numerical overflow.
911 @code{out-of-range}: the arguments to a procedure do not fall within the
915 @code{wrong-type-arg}: an argument to a procedure has the wrong type.
918 @code{wrong-number-of-args}: a procedure was called with the wrong number
922 @code{memory-allocation-error}: memory allocation error.
925 @code{stack-overflow}: stack overflow error.
928 @code{regex-error}: errors generated by the regular expression library.
931 @code{misc-error}: other errors.
935 @subsection C Support
937 SCM scm_error (SCM key, char *subr, char *message, SCM args, SCM rest)
939 Throws an error, after converting the char * arguments to Scheme strings.
940 subr is the Scheme name of the procedure, NULL is converted to #f.
941 Likewise a NULL message is converted to #f.
943 The following procedures invoke scm_error with various error keys and
944 arguments. The first three call scm_error with the system-error key
945 and automatically supply errno in the "rest" argument: scm_syserror
946 generates messages using strerror, scm_sysmissing is used when
947 facilities are not available. Care should be taken that the errno
948 value is not reset (e.g. due to an interrupt).
952 void scm_syserror (char *subr);
954 void scm_syserror_msg (char *subr, char *message, SCM args);
956 void scm_sysmissing (char *subr);
958 void scm_num_overflow (char *subr);
960 void scm_out_of_range (char *subr, SCM bad_value);
962 void scm_wrong_num_args (SCM proc);
964 void scm_wrong_type_arg (char *subr, int pos, SCM bad_value);
966 void scm_memory_error (char *subr);
968 static void scm_regex_error (char *subr, int code); (only used in rgx.c).
971 Exception handlers can also be installed from C, using
972 scm_internal_catch, scm_lazy_catch, or scm_stack_catch from
973 libguile/throw.c. These have not yet been documented, however the
974 source contains some useful comments.
978 @c TeX-master: "guile.texi"