Controlling the Flow of Program Execution
=========================================

See Control Flow for a discussion of how the more general control flow of Scheme affects C code.

Evaluating a Sequence of Expressions
------------------------------------

The begin syntax is used for grouping several expressions together so that they are treated as if they were one expression. This is particularly important when syntactic expressions are used which only allow one expression, but the programmer wants to use more than one expression in that place.  As an example, consider the conditional expression below:

     (if (> x 0)
         (begin (display "greater") (newline)))

If the two calls to display and newline were not embedded in a begin-statement, the call to newline would get misinterpreted as the else-branch of the if-expression.

 -- syntax: begin expr1 expr2 ...
     The expression(s) are evaluated in left-to-right order and the value of the last expression is returned as the value of the begin-expression.  This expression type is used when the expressions before the last one are evaluated for their side effects.

     Guile also allows the expression (begin), a begin with no sub-expressions.  Such an expression returns the `unspecified' value.

Simple Conditional Evaluation
-----------------------------

Guile provides three syntactic constructs for conditional evaluation. if is the normal if-then-else expression (with an optional else branch), cond is a conditional expression with multiple branches and case branches if an expression has one of a set of constant values.

 -- syntax: if test consequent [alternate]
     All arguments may be arbitrary expressions.  First, TEST is evaluated.  If it returns a true value, the expression CONSEQUENT is evaluated and ALTERNATE is ignored.  If TEST evaluates to #f, ALTERNATE is evaluated instead.  The value of the evaluated branch (CONSEQUENT or ALTERNATE) is returned as the value of the if expression.

     When ALTERNATE is omitted and the TEST evaluates to #f, the value of the expression is not specified.

 -- syntax: cond clause1 clause2 ...
     Each cond-clause must look like this:

          (TEST EXPRESSION ...)

     where TEST and EXPRESSION are arbitrary expression, or like this

          (TEST => EXPRESSION)

     where EXPRESSION must evaluate to a procedure.

     The TESTs of the clauses are evaluated in order and as soon as one of them evaluates to a true values, the corresponding EXPRESSIONs are evaluated in order and the last value is returned as the value of the cond-expression.  For the => clause type, EXPRESSION is evaluated and the resulting procedure is applied to the value of TEST.  The result of this procedure application is then the result of the cond-expression.

     One additional cond-clause is available as an extension to standard Scheme:

          (TEST GUARD => EXPRESSION)

     where GUARD and EXPRESSION must evaluate to procedures. For this clause type, TEST may return multiple values, and cond ignores its boolean state; instead, cond evaluates GUARD and applies the resulting procedure to the value(s) of TEST, as if GUARD were the CONSUMER argument of call-with-values.  Iff the result of that procedure call is a true value, it evaluates EXPRESSION and applies the resulting procedure to the value(s) of TEST, in the same manner as the GUARD was called.

     The TEST of the last CLAUSE may be the symbol else. Then, if none of the preceding TESTs is true, the EXPRESSIONs following the else are evaluated to produce the result of the cond-expression.

 -- syntax: case key clause1 clause2 ...
     KEY may be any expression, the CLAUSEs must have the form

          ((DATUM1 ...) EXPR1 EXPR2 ...)

     and the last CLAUSE may have the form

          (else EXPR1 EXPR2 ...)

     All DATUMs must be distinct.  First, KEY is evaluated.  The the result of this evaluation is compared against all DATUMs using eqv?.  When this comparison succeeds, the expression(s) following the DATUM are evaluated from left to right, returning the value of the last expression as the result of the case expression.

     If the KEY matches no DATUM and there is an else-clause, the expressions following the else are evaluated.  If there is no such clause, the result of the expression is unspecified.

Conditional Evaluation of a Sequence of Expressions
---------------------------------------------------

and and or evaluate all their arguments in order, similar to begin, but evaluation stops as soon as one of the expressions evaluates to false or true, respectively.

 -- syntax: and expr ...
     Evaluate the EXPRs from left to right and stop evaluation as soon as one expression evaluates to #f; the remaining expressions are not evaluated.  The value of the last evaluated expression is returned. If no expression evaluates to #f, the value of the last expression is returned.

     If used without expressions, #t is returned.

 -- syntax: or expr ...
     Evaluate the EXPRs from left to right and stop evaluation as soon as one expression evaluates to a true value (that is, a value different from #f); the remaining expressions are not evaluated.  The value of the last evaluated expression is returned.  If all expressions evaluate to #f, #f is returned.

     If used without expressions, #f is returned.

Iteration mechanisms
--------------------

Scheme has only few iteration mechanisms, mainly because iteration in Scheme programs is normally expressed using recursion.  Nevertheless, R5RS defines a construct for programming loops, calling do.  In addition, Guile has an explicit looping syntax called while.

 -- syntax: do ((variable init [step]) ...) (test [expr ...]) body ...
     Bind VARIABLEs and evaluate BODY until TEST is true. The return value is the last EXPR after TEST, if given.  A simple example will illustrate the basic form,

          (do ((i 1 (1+ i)))
              ((> i 4))
            (display i))
          -| 1234

     Or with two variables and a final return value,

          (do ((i 1 (1+ i))
               (p 3 (* 3 p)))
              ((> i 4)
               p)
            (format #t "3**~s is ~s\n" i p))
          -|
          3**1 is 3
          3**2 is 9
          3**3 is 27
          3**4 is 81
          =>
          789

     The VARIABLE bindings are established like a let, in that the expressions are all evaluated and then all bindings made.  When iterating, the optional STEP expressions are evaluated with the previous bindings in scope, then new bindings all made.

     The TEST expression is a termination condition.  Looping stops when the TEST is true.  It's evaluated before running the BODY each time, so if it's true the first time then BODY is not run at all.

     The optional EXPRs after the TEST are evaluated at the end of looping, with the final VARIABLE bindings available.  The last EXPR gives the return value, or if there are no EXPRs the return value is unspecified.

     Each iteration establishes bindings to fresh locations for the VARIABLEs, like a new let for each iteration.  This is done for VARIABLEs without STEP expressions too.  The following illustrates this, showing how a new i is captured by the lambda in each iteration (see The Concept of Closure).

          (define lst '())
          (do ((i 1 (1+ i)))
              ((> i 4))
            (set! lst (cons (lambda () i) lst)))
          (map (lambda (proc) (proc)) lst)
          =>
          (4 3 2 1)

 -- syntax: while cond body ...
     Run a loop executing the BODY forms while COND is true. COND is tested at the start of each iteration, so if it's #f the first time then BODY is not executed at all.  The return value is unspecified.

     Within while, two extra bindings are provided, they can be used from both COND and BODY.

      -- Scheme Procedure: break
          Break out of the while form.

      -- Scheme Procedure: continue
          Abandon the current iteration, go back to the start and test COND again, etc.

     Each while form gets its own break and continue procedures, operating on that while.  This means when loops are nested the outer break can be used to escape all the way out. For example,

          (while (test1)
            (let ((outer-break break))
              (while (test2)
                (if (something)
                  (outer-break #f))
                ...)))

     Note that each break and continue procedure can only be used within the dynamic extent of its while.  Outside the while their behaviour is unspecified.

Another very common way of expressing iteration in Scheme programs is the use of the so-called named let.

Named let is a variant of let which creates a procedure and calls it in one step.  Because of the newly created procedure, named let is more powerful than do--it can be used for iteration, but also for arbitrary recursion.

 -- syntax: let variable bindings body
     For the definition of BINDINGS see the documentation about let (see Local Bindings).

     Named let works as follows:

       * A new procedure which accepts as many arguments as are in BINDINGS is created and bound locally (using let) to VARIABLE.  The new procedure's formal argument names are the name of the VARIABLES.

       * The BODY expressions are inserted into the newly created procedure.

       * The procedure is called with the INIT expressions as the formal arguments.

     The next example implements a loop which iterates (by recursion) 1000 times.

          (let lp ((x 1000))
            (if (positive? x)
                (lp (- x 1))
                x))
          =>
          0

Continuations
-------------

A ``continuation'' is the code that will execute when a given function or expression returns.  For example, consider

     (define (foo)
       (display "hello\n")
       (display (bar)) (newline)
       (exit))

The continuation from the call to bar comprises a display of the value returned, a newline and an exit.  This can be expressed as a function of one argument.

     (lambda (r)
       (display r) (newline)
       (exit))

In Scheme, continuations are represented as special procedures just like this.  The special property is that when a continuation is called it abandons the current program location and jumps directly to that represented by the continuation.

A continuation is like a dynamic label, capturing at run-time a point in program execution, including all the nested calls that have lead to it (or rather the code that will execute when those calls return).

Continuations are created with the following functions.

 -- Scheme Procedure: call-with-current-continuation proc
 -- Scheme Procedure: call/cc proc
     Capture the current continuation and call (PROC CONT) with it.  The return value is the value returned by PROC, or when (CONT VALUE) is later invoked, the return is the VALUE passed.

     Normally CONT should be called with one argument, but when the location resumed is expecting multiple values (see Multiple Values) then they should be passed as multiple arguments, for instance (CONT X Y Z).

     CONT may only be used from the same side of a continuation barrier as it was created (see Continuation Barriers), and in a multi-threaded program only from the thread in which it was created.

     The call to PROC is not part of the continuation captured, it runs only when the continuation is created.  Often a program will want to store CONT somewhere for later use; this can be done in PROC.

     The call in the name call-with-current-continuation refers to the way a call to PROC gives the newly created continuation.  It's not related to the way a call is used later to invoke that continuation.

     call/cc is an alias for call-with-current-continuation. This is in common use since the latter is rather long.

 -- C Function: SCM scm_make_continuation (int *first)
     Capture the current continuation as described above.  The return value is the new continuation, and *FIRST is set to 1.

     When the continuation is invoked, scm_make_continuation will return again, this time returning the value (or set of multiple values) passed in that invocation, and with *FIRST set to 0.

Here is a simple example,

     (define kont #f)
     (format #t "the return is ~a\n"
             (call/cc (lambda (k)
                        (set! kont k)
                        1)))
     => the return is 1

     (kont 2)
     => the return is 2

call/cc captures a continuation in which the value returned is going to be displayed by format.  The lambda stores this in kont and gives an initial return 1 which is displayed.  The later invocation of kont resumes the captured point, but this time returning 2, which is displayed.

When Guile is run interactively, a call to format like this has an implicit return back to the read-eval-print loop.  call/cc captures that like any other return, which is why interactively kont will come back to read more input.

C programmers may note that call/cc is like setjmp in the way it records at runtime a point in program execution.  A call to a continuation is like a longjmp in that it abandons the present location and goes to the recorded one.  Like longjmp, the value passed to the continuation is the value returned by call/cc on resuming there.  However longjmp can only go up the program stack, but the continuation mechanism can go anywhere.

When a continuation is invoked, call/cc and subsequent code effectively ``returns'' a second time.  It can be confusing to imagine a function returning more times than it was called.  It may help instead to think of it being stealthily re-entered and then program flow going on as normal.

dynamic-wind (see Dynamic Wind) can be used to ensure setup and cleanup code is run when a program locus is resumed or abandoned through the continuation mechanism.

Continuations are a powerful mechanism, and can be used to implement almost any sort of control structure, such as loops, coroutines, or exception handlers.

However the implementation of continuations in Guile is not as efficient as one might hope, because Guile is designed to cooperate with programs written in other languages, such as C, which do not know about continuations.  Basically continuations are captured by a block copy of the stack, and resumed by copying back.

For this reason, generally continuations should be used only when there is no other simple way to achieve the desired result, or when the elegance of the continuation mechanism outweighs the need for performance.

Escapes upwards from loops or nested functions are generally best handled with exceptions (see Exceptions).  Coroutines can be efficiently implemented with cooperating threads (a thread holds a full program stack but doesn't copy it around the way continuations do).

Returning and Accepting Multiple Values
---------------------------------------

Scheme allows a procedure to return more than one value to its caller. This is quite different to other languages which only allow single-value returns.  Returning multiple values is different from returning a list (or pair or vector) of values to the caller, because conceptually not one compound object is returned, but several distinct values.

The primitive procedures for handling multiple values are values and call-with-values.  values is used for returning multiple values from a procedure.  This is done by placing a call to values with zero or more arguments in tail position in a procedure body.  call-with-values combines a procedure returning multiple values with a procedure which accepts these values as parameters.

 -- Scheme Procedure: values arg1 ... argN
 -- C Function: scm_values (args)
     Delivers all of its arguments to its continuation.  Except for continuations created by the call-with-values procedure, all continuations take exactly one value.  The effect of passing no value or more than one value to continuations that were not created by call-with-values is unspecified.

     For scm_values, ARGS is a list of arguments and the return is a multiple-values object which the caller can return.  In the current implementation that object shares structure with ARGS, so ARGS should not be modified subsequently.

 -- Scheme Procedure: call-with-values producer consumer
     Calls its PRODUCER argument with no values and a continuation that, when passed some values, calls the CONSUMER procedure with those values as arguments.  The continuation for the call to CONSUMER is the continuation of the call to call-with-values.

          (call-with-values (lambda () (values 4 5))
                            (lambda (a b) b))
          => 5

          (call-with-values * -)
          => -1

In addition to the fundamental procedures described above, Guile has a module which exports a syntax called receive, which is much more convenient.  If you want to use it in your programs, you have to load the module (ice-9 receive) with the statement

     (use-modules (ice-9 receive))

 -- library syntax: receive formals expr body ...
     Evaluate the expression EXPR, and bind the result values (zero or more) to the formal arguments in the formal argument list FORMALS. FORMALS must have the same syntax like the formal argument list used in lambda (see Lambda).  After binding the variables, the expressions in BODY ... are evaluated in order.

Exceptions
----------

A common requirement in applications is to want to jump non-locally from the depths of a computation back to, say, the application's main processing loop.  Usually, the place that is the target of the jump is somewhere in the calling stack of procedures that called the procedure that wants to jump back.  For example, typical logic for a key press driven application might look something like this:

     main-loop:
       read the next key press and call dispatch-key

     dispatch-key:
       lookup the key in a keymap and call an appropriate procedure,
       say find-file

     find-file:
       interactively read the required file name, then call
       find-specified-file

     find-specified-file:
       check whether file exists; if not, jump back to main-loop
       ...

The jump back to main-loop could be achieved by returning through the stack one procedure at a time, using the return value of each procedure to indicate the error condition, but Guile (like most modern programming languages) provides an additional mechanism called exception handling that can be used to implement such jumps much more conveniently.

Exception Terminology
.....................

There are several variations on the terminology for dealing with non-local jumps.  It is useful to be aware of them, and to realize that they all refer to the same basic mechanism.

  * Actually making a non-local jump may be called raising an exception, raising a signal, throwing an exception or doing a long jump.  When the jump indicates an error condition, people may talk about signalling, raising or throwing an error.

  * Handling the jump at its target may be referred to as catching or handling the exception, signal or, where an error condition is involved, error.

Where signal and signalling are used, special care is needed to avoid the risk of confusion with POSIX signals.

This manual prefers to speak of throwing and catching exceptions, since this terminology matches the corresponding Guile primitives.

Catching Exceptions
...................

catch is used to set up a target for a possible non-local jump. The arguments of a catch expression are a key, which restricts the set of exceptions to which this catch applies, a thunk that specifies the code to execute and one or two handler procedures that say what to do if an exception is thrown while executing the code.  If the execution thunk executes normally, which means without throwing any exceptions, the handler procedures are not called at all.

When an exception is thrown using the throw function, the first argument of the throw is a symbol that indicates the type of the exception.  For example, Guile throws an exception using the symbol numerical-overflow to indicate numerical overflow errors such as division by zero:

     (/ 1 0)
     =>
     ABORT: (numerical-overflow)

The KEY argument in a catch expression corresponds to this symbol.  KEY may be a specific symbol, such as numerical-overflow, in which case the catch applies specifically to exceptions of that type; or it may be #t, which means that the catch applies to all exceptions, irrespective of their type.

The second argument of a catch expression should be a thunk (i.e. a procedure that accepts no arguments) that specifies the normal case code.  The catch is active for the execution of this thunk, including any code called directly or indirectly by the thunk's body. Evaluation of the catch expression activates the catch and then calls this thunk.

The third argument of a catch expression is a handler procedure. If an exception is thrown, this procedure is called with exactly the arguments specified by the throw.  Therefore, the handler procedure must be designed to accept a number of arguments that corresponds to the number of arguments in all throw expressions that can be caught by this catch.

The fourth, optional argument of a catch expression is another handler procedure, called the pre-unwind handler.  It differs from the third argument in that if an exception is thrown, it is called, before the third argument handler, in exactly the dynamic context of the throw expression that threw the exception.  This means that it is useful for capturing or displaying the stack at the point of the throw, or for examining other aspects of the dynamic context, such as fluid values, before the context is unwound back to that of the prevailing catch.

 -- Scheme Procedure: catch key thunk handler [pre-unwind-handler]
 -- C Function: scm_catch_with_pre_unwind_handler (key, thunk, handler, pre_unwind_handler)
 -- C Function: scm_catch (key, thunk, handler)
     Invoke THUNK in the dynamic context of HANDLER for exceptions matching KEY.  If thunk throws to the symbol KEY, then HANDLER is invoked this way:

          (handler key args ...)

     KEY is a symbol or #t.

     THUNK takes no arguments.  If THUNK returns normally, that is the return value of catch.

     Handler is invoked outside the scope of its own catch. If HANDLER again throws to the same key, a new handler from further up the call chain is invoked.

     If the key is #t, then a throw to any symbol will match this call to catch.

     If a PRE-UNWIND-HANDLER is given and THUNK throws an exception that matches KEY, Guile calls the PRE-UNWIND-HANDLER before unwinding the dynamic state and invoking the main HANDLER.  PRE-UNWIND-HANDLER should be a procedure with the same signature as HANDLER, that is (lambda (key . args)).  It is typically used to save the stack at the point where the exception occurred, but can also query other parts of the dynamic state at that point, such as fluid values.

     A PRE-UNWIND-HANDLER can exit either normally or non-locally. If it exits normally, Guile unwinds the stack and dynamic context and then calls the normal (third argument) handler.  If it exits non-locally, that exit determines the continuation.

If a handler procedure needs to match a variety of throw expressions with varying numbers of arguments, you should write it like this:

     (lambda (key . args)
       ...)

The KEY argument is guaranteed always to be present, because a throw without a KEY is not valid.  The number and interpretation of the ARGS varies from one type of exception to another, but should be specified by the documentation for each exception type.

Note that, once the normal (post-unwind) handler procedure is invoked, the catch that led to the handler procedure being called is no longer active.  Therefore, if the handler procedure itself throws an exception, that exception can only be caught by another active catch higher up the call stack, if there is one.

 -- C Function: SCM scm_c_catch (SCM tag, scm_t_catch_body body, void *body_data, scm_t_catch_handler handler, void *handler_data, scm_t_catch_handler pre_unwind_handler, void *pre_unwind_handler_data)
 -- C Function: SCM scm_internal_catch (SCM tag, scm_t_catch_body body, void *body_data, scm_t_catch_handler handler, void *handler_data)
     The above scm_catch_with_pre_unwind_handler and scm_catch take Scheme procedures as body and handler arguments. scm_c_catch and scm_internal_catch are equivalents taking C functions.

     BODY is called as BODY (BODY_DATA) with a catch on exceptions of the given TAG type.  If an exception is caught, PRE_UNWIND_HANDLER and HANDLER are called as HANDLER (HANDLER_DATA, KEY, ARGS). KEY and ARGS are the SCM key and argument list from the throw.

     BODY and HANDLER should have the following prototypes. scm_t_catch_body and scm_t_catch_handler are pointer typedefs for these.

          SCM body (void *data);
          SCM handler (void *data, SCM key, SCM args);

     The BODY_DATA and HANDLER_DATA parameters are passed to the respective calls so an application can communicate extra information to those functions.

     If the data consists of an SCM object, care should be taken that it isn't garbage collected while still required.  If the SCM is a local C variable, one way to protect it is to pass a pointer to that variable as the data parameter, since the C compiler will then know the value must be held on the stack.  Another way is to use scm_remember_upto_here_1 (see Remembering During Operations).

Throw Handlers
..............

It's sometimes useful to be able to intercept an exception that is being thrown, but without changing where in the dynamic context that exception will eventually be caught.  This could be to clean up some related state or to pass information about the exception to a debugger, for example. The with-throw-handler procedure provides a way to do this.

 -- Scheme Procedure: with-throw-handler key thunk handler
 -- C Function: scm_with_throw_handler (key, thunk, handler)
     Add HANDLER to the dynamic context as a throw handler for key KEY, then invoke THUNK.

 -- C Function: SCM scm_c_with_throw_handler (SCM tag, scm_t_catch_body body, void *body_data, scm_t_catch_handler handler, void *handler_data, int lazy_catch_p)
     The above scm_with_throw_handler takes Scheme procedures as body (thunk) and handler arguments.  scm_c_with_throw_handler is an equivalent taking C functions.  See scm_c_catch (see Catch) for a description of the parameters, the behaviour however of course follows with-throw-handler.

If THUNK throws an exception, Guile handles that exception by invoking the innermost catch or throw handler whose key matches that of the exception.  When the innermost thing is a throw handler, Guile calls the specified handler procedure using (apply HANDLER key args).  The handler procedure may either return normally or exit non-locally.  If it returns normally, Guile passes the exception on to the next innermost catch or throw handler.  If it exits non-locally, that exit determines the continuation.

The behaviour of a throw handler is very similar to that of a catch expression's optional pre-unwind handler.  In particular, a throw handler's handler procedure is invoked in the exact dynamic context of the throw expression, just as a pre-unwind handler is. with-throw-handler may be seen as a half-catch: it does everything that a catch would do until the point where catch would start unwinding the stack and dynamic context, but then it rethrows to the next innermost catch or throw handler instead.

Catch Without Unwinding
.......................

Before version 1.8, Guile's closest equivalent to with-throw-handler was lazy-catch.  From version 1.8 onwards we recommend using with-throw-handler because its behaviour is more useful than that of lazy-catch, but lazy-catch is still supported as well.

A lazy catch is used in the same way as a normal catch, with KEY, THUNK and HANDLER arguments specifying the exception type, normal case code and handler procedure, but differs in one important respect: the handler procedure is executed without unwinding the call stack from the context of the throw expression that caused the handler to be invoked.

 -- Scheme Procedure: lazy-catch key thunk handler
 -- C Function: scm_lazy_catch (key, thunk, handler)
     This behaves exactly like catch, except that it does not unwind the stack before invoking HANDLER. If the HANDLER procedure returns normally, Guile rethrows the same exception again to the next innermost catch, lazy-catch or throw handler.  If the HANDLER exits non-locally, that exit determines the continuation.

 -- 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)
     The above scm_lazy_catch takes Scheme procedures as body and handler arguments.  scm_internal_lazy_catch is an equivalent taking C functions.  See scm_internal_catch (see Catch) for a description of the parameters, the behaviour however of course follows lazy-catch.

Typically HANDLER is used to display a backtrace of the stack at the point where the corresponding throw occurred, or to save off this information for possible display later.

Not unwinding the stack means that throwing an exception that is caught by a lazy-catch is almost equivalent to calling the lazy-catch's handler inline instead of each throw, and then omitting the surrounding lazy-catch.  In other words,

     (lazy-catch 'key
       (lambda () ... (throw 'key args ...) ...)
       handler)

is almost equivalent to

     ((lambda () ... (handler 'key args ...) ...))

But why only almost?  The difference is that with lazy-catch (as with normal catch), the dynamic context is unwound back to just outside the lazy-catch expression before invoking the handler.  (For an introduction to what is meant by dynamic context, see Dynamic Wind.)

Then, when the handler itself throws an exception, that exception must be caught by some kind of catch (including perhaps another lazy-catch) higher up the call stack.

The dynamic context also includes with-fluids blocks (see Fluids and Dynamic States), so the effect of unwinding the dynamic context can also be seen in fluid variable values.  This is illustrated by the following code, in which the normal case thunk uses with-fluids to temporarily change the value of a fluid:

     (define f (make-fluid))
     (fluid-set! f "top level value")

     (define (handler . args)
       (cons (fluid-ref f) args))

     (lazy-catch 'foo
                 (lambda ()
                   (with-fluids ((f "local value"))
                     (throw 'foo)))
                 handler)
     =>
     ("top level value" foo)

     ((lambda ()
        (with-fluids ((f "local value"))
          (handler 'foo))))
     =>
     ("local value" foo)

In the lazy-catch version, the unwinding of dynamic context restores f to its value outside the with-fluids block before the handler is invoked, so the handler's (fluid-ref f) returns the external value.

lazy-catch is useful because it permits the implementation of debuggers and other reflective programming tools that need to access the state of the call stack at the exact point where an exception or an error is thrown.  For an example of this, see REFFIXME:stack-catch.

It should be obvious from the above that lazy-catch is very similar to with-throw-handler.  In fact Guile implements lazy-catch in exactly the same way as with-throw-handler, except with a flag set to say ``where there are slight differences between what with-throw-handler and lazy-catch would do, do what lazy-catch has always done''.  There are two such differences:

 1. with-throw-handler handlers execute in the full dynamic context of the originating throw call.  lazy-catch handlers execute in the dynamic context of the lazy-catch expression, excepting only that the stack has not yet been unwound from the point of the throw call.

 2. If a with-throw-handler handler throws to a key that does not match the with-throw-handler expression's KEY, the new throw may be handled by a catch or throw handler that is _closer_ to the throw than the first with-throw-handler.  If a lazy-catch handler throws, it will always be handled by a catch or throw handler that is higher up the dynamic context than the first lazy-catch.

Here is an example to illustrate the second difference:

     (catch 'a
       (lambda ()
         (with-throw-handler 'b
           (lambda ()
             (catch 'a
               (lambda ()
                 (throw 'b))
               inner-handler))
           (lambda (key . args)
             (throw 'a))))
       outer-handler)

This code will call inner-handler and then continue with the continuation of the inner catch.  If the with-throw-handler was changed to lazy-catch, however, the code would call outer-handler and then continue with the continuation of the outer catch.

Modulo these two differences, any statements in the previous and following subsections about throw handlers apply to lazy catches as well.

Throwing Exceptions
...................

The throw primitive is used to throw an exception.  One argument, the KEY, is mandatory, and must be a symbol; it indicates the type of exception that is being thrown.  Following the KEY, throw accepts any number of additional arguments, whose meaning depends on the exception type.  The documentation for each possible type of exception should specify the additional arguments that are expected for that kind of exception.

 -- Scheme Procedure: throw key . args
 -- C Function: scm_throw (key, args)
     Invoke the catch form matching KEY, passing ARGS to the HANDLER.

     KEY is a symbol.  It will match catches of the same symbol or of #t.

     If there is no handler at all, Guile prints an error and then exits.

When an exception is thrown, it will be caught by the innermost catch or throw handler that applies to the type of the thrown exception; in other words, whose KEY is either #t or the same symbol as that used in the throw expression.  Once Guile has identified the appropriate catch or throw handler, it handles the exception by applying the relevant handler procedure(s) to the arguments of the throw.

If there is no appropriate catch or throw handler for a thrown exception, Guile prints an error to the current error port indicating an uncaught exception, and then exits.  In practice, it is quite difficult to observe this behaviour, because Guile when used interactively installs a top level catch handler that will catch all exceptions and print an appropriate error message without exiting.  For example, this is what happens if you try to throw an unhandled exception in the standard Guile REPL; note that Guile's command loop continues after the error message:

     guile> (throw 'badex)
     <unnamed port>:3:1: In procedure gsubr-apply ...
     <unnamed port>:3:1: unhandled-exception: badex
     ABORT: (misc-error)
     guile>

The default uncaught exception behaviour can be observed by evaluating a throw expression from the shell command line:

     $ guile -c "(begin (throw 'badex) (display \"here\\n\"))"
     guile: uncaught throw to badex: ()
     $

That Guile exits immediately following the uncaught exception is shown by the absence of any output from the display expression, because Guile never gets to the point of evaluating that expression.

How Guile Implements Exceptions
...............................

It is traditional in Scheme to implement exception systems using call-with-current-continuation.  Continuations (see Continuations) are such a powerful concept that any other control mechanism --- including catch and throw --- can be implemented in terms of them.

Guile does not implement catch and throw like this, though.  Why not?  Because Guile is specifically designed to be easy to integrate with applications written in C.  In a mixed Scheme/C environment, the concept of continuation must logically include ``what happens next'' in the C parts of the application as well as the Scheme parts, and it turns out that the only reasonable way of implementing continuations like this is to save and restore the complete C stack.

So Guile's implementation of call-with-current-continuation is a stack copying one.  This allows it to interact well with ordinary C code, but means that creating and calling a continuation is slowed down by the time that it takes to copy the C stack.

The more targeted mechanism provided by catch and throw does not need to save and restore the C stack because the throw always jumps to a location higher up the stack of the code that executes the throw.  Therefore Guile implements the catch and throw primitives independently of call-with-current-continuation, in a way that takes advantage of this upwards only nature of exceptions.

Procedures for Signaling Errors
-------------------------------

Guile provides a set of convenience procedures for signaling error conditions that are implemented on top of the exception primitives just described.

 -- Scheme Procedure: error msg args ...
     Raise an error with key misc-error and a message constructed by displaying MSG and writing ARGS.

 -- Scheme Procedure: scm-error key subr message args data
 -- C Function: scm_error_scm (key, subr, message, args, data)
     Raise an error with key KEY.  SUBR can be a string naming the procedure associated with the error, or #f. MESSAGE is the error message string, possibly containing ~S and ~A escapes.  When an error is reported, these are replaced by formatting the corresponding members of ARGS: ~A (was %s in older versions of Guile) formats using display and ~S (was %S) formats using write.  DATA is a list or #f depending on KEY: if KEY is system-error then it should be a list containing the Unix errno value; If KEY is signal then it should be a list containing the Unix signal number; If KEY is out-of-range or wrong-type-arg, it is a list containing the bad value; otherwise it will usually be #f.

 -- Scheme Procedure: strerror err
 -- C Function: scm_strerror (err)
     Return the Unix error message corresponding to ERR, an integer errno value.

     When setlocale has been called (see Locales), the message is in the language and charset of LC_MESSAGES.  (This is done by the C library.)

 -- syntax: false-if-exception expr
     Returns the result of evaluating its argument; however if an exception occurs then #f is returned instead.

Dynamic Wind
------------

For Scheme code, the fundamental procedure to react to non-local entry and exits of dynamic contexts is dynamic-wind.  C code could use scm_internal_dynamic_wind, but since C does not allow the convenient construction of anonymous procedures that close over lexical variables, this will be, well, inconvenient.

Therefore, Guile offers the functions scm_dynwind_begin and scm_dynwind_end to delimit a dynamic extent.  Within this dynamic extent, which is calles a dynwind context, you can perform various dynwind actions that control what happens when the dynwind context is entered or left.  For example, you can register a cleanup routine with scm_dynwind_unwind_handler that is executed when the context is left.  There are several other more specialized dynwind actions as well, for example to temporarily block the execution of asyncs or to temporarily change the current output port.  They are described elsewhere in this manual.

Here is an example that shows how to prevent memory leaks.

     /* Suppose there is a function called FOO in some library that you
        would like to make available to Scheme code (or to C code that
        follows the Scheme conventions).

        FOO takes two C strings and returns a new string.  When an error has
        occurred in FOO, it returns NULL.
     */

     char *foo (char *s1, char *s2);

     /* SCM_FOO interfaces the C function FOO to the Scheme way of life.
        It takes care to free up all temporary strings in the case of
        non-local exits.
      */

     SCM
     scm_foo (SCM s1, SCM s2)
     {
       char *c_s1, *c_s2, *c_res;

       scm_dynwind_begin (0);

       c_s1 = scm_to_locale_string (s1);

       /* Call 'free (c_s1)' when the dynwind context is left.
       */
       scm_dynwind_unwind_handler (free, c_s1, SCM_F_WIND_EXPLICITLY);

       c_s2 = scm_to_locale_string (s2);

       /* Same as above, but more concisely.
       */
       scm_dynwind_free (c_s2);

       c_res = foo (c_s1, c_s2);
       if (c_res == NULL)
         scm_memory_error ("foo");

       scm_dynwind_end ();

       return scm_take_locale_string (res);
     }

 -- Scheme Procedure: dynamic-wind in_guard thunk out_guard
 -- C Function: scm_dynamic_wind (in_guard, thunk, out_guard)
     All three arguments must be 0-argument procedures. IN_GUARD is called, then THUNK, then OUT_GUARD.

     If, any time during the execution of THUNK, the dynamic extent of the dynamic-wind expression is escaped non-locally, OUT_GUARD is called.  If the dynamic extent of the dynamic-wind is re-entered, IN_GUARD is called.  Thus IN_GUARD and OUT_GUARD may be called any number of times.

          (define x 'normal-binding)
          => x
          (define a-cont  (call-with-current-continuation
                            (lambda (escape)
                               (let ((old-x x))
                                 (dynamic-wind
                                    ;; in-guard:
                                    ;;
                                    (lambda () (set! x 'special-binding))

                                    ;; thunk
                                    ;;
                                    (lambda () (display x) (newline)
                                               (call-with-current-continuation escape)
                                               (display x) (newline)
                                               x)

                                    ;; out-guard:
                                    ;;
                                    (lambda () (set! x old-x)))))))

          ;; Prints:
          special-binding
          ;; Evaluates to:
          => a-cont
          x
          => normal-binding
          (a-cont #f)
          ;; Prints:
          special-binding
          ;; Evaluates to:
          => a-cont  ;; the value of the (define a-cont...)
          x
          => normal-binding
          a-cont
          => special-binding

 -- C Type: scm_t_dynwind_flags
     This is an enumeration of several flags that modify the behavior of scm_dynwind_begin.  The flags are listed in the following table.

     SCM_F_DYNWIND_REWINDABLE
          The dynamic context is rewindable.  This means that it can be reentered non-locally (via the invokation of a continuation).  The default is that a dynwind context can not be reentered non-locally.

 -- C Function: void scm_dynwind_begin (scm_t_dynwind_flags flags)
     The function scm_dynwind_begin starts a new dynamic context and makes it the `current' one.

     The FLAGS argument determines the default behavior of the context.  Normally, use 0.  This will result in a context that can not be reentered with a captured continuation.  When you are prepared to handle reentries, include SCM_F_DYNWIND_REWINDABLE in FLAGS.

     Being prepared for reentry means that the effects of unwind handlers can be undone on reentry.  In the example above, we want to prevent a memory leak on non-local exit and thus register an unwind handler that frees the memory.  But once the memory is freed, we can not get it back on reentry.  Thus reentry can not be allowed.

     The consequence is that continuations become less useful when non-reenterable contexts are captured, but you don't need to worry about that too much.

     The context is ended either implicitly when a non-local exit happens, or explicitly with scm_dynwind_end.  You must make sure that a dynwind context is indeed ended properly.  If you fail to call scm_dynwind_end for each scm_dynwind_begin, the behavior is undefined.

 -- C Function: void scm_dynwind_end ()
     End the current dynamic context explicitly and make the previous one current.

 -- C Type: scm_t_wind_flags
     This is an enumeration of several flags that modify the behavior of scm_dynwind_unwind_handler and scm_dynwind_rewind_handler.  The flags are listed in the following table.

     SCM_F_WIND_EXPLICITLY
          The registered action is also carried out when the dynwind context is entered or left locally.

 -- C Function: void scm_dynwind_unwind_handler (void (*func)(void *), void *data, scm_t_wind_flags flags)
 -- C Function: void scm_dynwind_unwind_handler_with_scm (void (*func)(SCM), SCM data, scm_t_wind_flags flags)
     Arranges for FUNC to be called with DATA as its arguments when the current context ends implicitly.  If FLAGS contains SCM_F_WIND_EXPLICITLY, FUNC is also called when the context ends explicitly with scm_dynwind_end.

     The function scm_dynwind_unwind_handler_with_scm takes care that DATA is protected from garbage collection.

 -- C Function: void scm_dynwind_rewind_handler (void (*func)(void *), void *data, scm_t_wind_flags flags)
 -- C Function: void scm_dynwind_rewind_handler_with_scm (void (*func)(SCM), SCM data, scm_t_wind_flags flags)
     Arrange for FUNC to be called with DATA as its argument when the current context is restarted by rewinding the stack.  When FLAGS contains SCM_F_WIND_EXPLICITLY, FUNC is called immediately as well.

     The function scm_dynwind_rewind_handler_with_scm takes care that DATA is protected from garbage collection.

How to Handle Errors
--------------------

Error handling is based on catch and throw.  Errors are always thrown with a KEY and four arguments:

  * KEY: a symbol which indicates the type of error.  The symbols used by libguile are listed below.

  * SUBR: the name of the procedure from which the error is thrown, or #f.

  * MESSAGE: a string (possibly language and system dependent) describing the error.  The tokens ~A and ~S can be embedded within the message: they will be replaced with members of the ARGS list when the message is printed.  ~A indicates an argument printed using display, while ~S indicates an argument printed using write.  MESSAGE can also be #f, to allow it to be derived from the KEY by the error handler (may be useful if the KEY is to be thrown from both C and Scheme).

  * ARGS: a list of arguments to be used to expand ~A and ~S tokens in MESSAGE.  Can also be #f if no arguments are required.

  * REST: a list of any additional objects required. e.g., when the key is 'system-error, this contains the C errno value.  Can also be #f if no additional objects are required.

In addition to catch and throw, the following Scheme facilities are available:

 -- Scheme Procedure: display-error stack port subr message args rest
 -- C Function: scm_display_error (stack, port, subr, message, args, rest)
     Display an error message to the output port PORT. STACK is the saved stack for the error, SUBR is the name of the procedure in which the error occurred and MESSAGE is the actual error message, which may contain formatting instructions. These will format the arguments in the list ARGS accordingly.  REST is currently ignored.

The following are the error keys defined by libguile and the situations in which they are used:

  * error-signal: thrown after receiving an unhandled fatal signal such as SIGSEGV, SIGBUS, SIGFPE etc.  The REST argument in the throw contains the coded signal number (at present this is not the same as the usual Unix signal number).

  * system-error: thrown after the operating system indicates an error condition.  The REST argument in the throw contains the errno value.

  * numerical-overflow: numerical overflow.

  * out-of-range: the arguments to a procedure do not fall within the accepted domain.

  * wrong-type-arg: an argument to a procedure has the wrong type.

  * wrong-number-of-args: a procedure was called with the wrong number of arguments.

  * memory-allocation-error: memory allocation error.

  * stack-overflow: stack overflow error.

  * regular-expression-syntax: errors generated by the regular expression library.

  * misc-error: other errors.

C Support
.........

In the following C functions, SUBR and MESSAGE parameters can be NULL to give the effect of #f described above.

 -- C Function: SCM scm_error (SCM KEY, char *SUBR, char *MESSAGE, SCM ARGS, SCM REST)
     Throw an error, as per scm-error above.

 -- C Function: void scm_syserror (char *SUBR)
 -- C Function: void scm_syserror_msg (char *SUBR, char *MESSAGE, SCM ARGS)
     Throw an error with key system-error and supply errno in the REST argument.  For scm_syserror the message is generated using strerror.

     Care should be taken that any code in between the failing operation and the call to these routines doesn't change errno.

 -- C Function: void scm_num_overflow (char *SUBR)
 -- C Function: void scm_out_of_range (char *SUBR, SCM BAD_VALUE)
 -- C Function: void scm_wrong_num_args (SCM PROC)
 -- C Function: void scm_wrong_type_arg (char *SUBR, int ARGNUM, SCM BAD_VALUE)
 -- C Function: void scm_memory_error (char *SUBR)
     Throw an error with the various keys described above.

     For scm_wrong_num_args, PROC should be a Scheme symbol which is the name of the procedure incorrectly invoked.