Added Copyright notice.
[bpt/guile.git] / doc / ref / scheme-control.texi
CommitLineData
2da09c3f
MV
1@c -*-texinfo-*-
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.
6
a0e07ba4
NJ
7@page
8@node Control Mechanisms
9@chapter Controlling the Flow of Program Execution
10
42155d75
MV
11@menu
12* begin:: Evaluating a sequence of expressions.
13* if cond case:: Simple conditional evaluation.
14* and or:: Conditional evaluation of a sequence.
15* while do:: Iteration mechanisms.
16* Continuations:: Continuations.
17* Multiple Values:: Returning and accepting multiple values.
18* Exceptions:: Throwing and catching exceptions.
19* Error Reporting:: Procedures for signaling errors.
20* Dynamic Wind:: Guarding against non-local entrance/exit.
21* Frames:: Another way to handle non-localness
22* Handling Errors:: How to handle errors in C code.
23@end menu
24
86272eed
MV
25Scheme has a more general view of program flow than C, both locally and
26non-locally.
27
28Controlling the local flow of control involves things like gotos, loops,
29calling functions and returning from them. Non-local control flow
30refers to situations where the program jumps across one or more levels
31of function activations without using the normal call or return
32operations.
33
42155d75
MV
34The primitive means of C for local control flow is the @code{goto}
35statement, together with @code{if}. Loops done with @code{for},
36@code{while} or @code{do} could in principle be rewritten with just
37@code{goto} and @code{if}. In Scheme, the primitive means for local
38control flow is the @emph{function call} (together with @code{if}).
39Thus, the repetition of some computation in a loop is ultimately
40implemented by a function that calls itself, that is, by recursion.
41
42This approach is theoretically very powerful since it is easier to
43reason formally about recursion than about gotos. In C, using
44recursion exclusively would not be practical, tho, since it would eat
45up the stack very quickly. In Scheme, however, it is practical:
46function calls that appear in a @dfn{tail position} do not use any
47additional stack space.
48
49A function call is in a tail position when it is the last thing the
50calling function does. The value returned by the called function is
51immediately returned from the calling function. In the following
52example, the call to @code{bar-1} is in a tail position, while the
53call to @code{bar-2} is not. (The call to @code{1-} in @code{foo-2}
54is in a tail position, tho.)
55
56@lisp
57(define (foo-1 x)
58 (bar-1 (1- x)))
59
60(define (foo-2 x)
61 (1- (bar-2 x)))
62@end lisp
63
64Thus, when you take care to recurse only in tail positions, the
65recursion will only use constant stack space and will be as good as a
66loop constructed from gotos.
67
68Scheme offers a few syntactic abstractions (@code{do} and @dfn{named}
69@code{let}) that make writing loops slightly easier.
70
71But only Scheme functions can call other functions in a tail position:
72C functions can not. This matters when you have, say, two functions
73that call each other recursively to form a common loop. The following
74(unrealistic) example shows how one might go about determing whether a
75non-negative integer @var{n} is even or odd.
76
77@lisp
78(define (my-even? n)
79 (cond ((zero? n) #t)
80 (else (my-odd? (1- n)))))
81
82(define (my-odd? n)
83 (cond ((zero? n) #f)
84 (else (my-even? (1- n)))))
85@end lisp
86
87Because the calls to @code{my-even?} and @code{my-odd?} are in tail
88positions, these two procedures can be applied to arbitrary large
89integers without overflowing the stack. (They will still take a lot
90of time, of course.)
91
92However, when one or both of the two procedures would be rewritten in
93C, it could no longer call its companion in a tail position (since C
94does not have this concept). You might need to take this
95consideration into account when deciding which parts of your program
96to write in Scheme and which in C.
86272eed
MV
97
98In addition to calling functions and returning from them, a Scheme
99program can also exit non-locally from a function so that the control
100flow returns directly to an outer level. This means that some functions
101might not return at all.
102
103Even more, it is not only possible to jump to some outer level of
104control, a Scheme program can also jump back into the middle of a
105function that has already exited. This might cause some functions to
106return more than once.
107
108In general, these non-local jumps are done by invoking
e911f3ff 109@dfn{continuations} that have previously been captured using
86272eed
MV
110@code{call-with-current-continuation}. Guile also offers a slightly
111restricted set of functions, @code{catch} and @code{throw}, that can
112only be used for non-local exits. This restriction makes them more
42155d75
MV
113efficient. Error reporting (with the function @code{error}) is
114implemented by invoking @code{throw}, for example. The functions
115@code{catch} and @code{throw} belong to the topic of @dfn{exceptions}.
86272eed
MV
116
117Since Scheme functions can call C functions and vice versa, C code can
42155d75 118experience the more general control flow of Scheme as well. It is
86272eed
MV
119possible that a C function will not return at all, or will return more
120than once. While C does offer @code{setjmp} and @code{longjmp} for
42155d75
MV
121non-local exits, it is still an unusual thing for C code. In
122contrast, non-local exits are very common in Scheme, mostly to report
123errors.
86272eed
MV
124
125You need to be prepared for the non-local jumps in the control flow
126whenever you use a function from @code{libguile}: it is best to assume
127that any @code{libguile} function might signal an error or run a pending
128signal handler (which in turn can do arbitrary things).
129
130It is often necessary to take cleanup actions when the control leaves a
131function non-locally. Also, when the control returns non-locally, some
132setup actions might be called for. For example, the Scheme function
133@code{with-output-to-port} needs to modify the global state so that
134@code{current-output-port} returns the port passed to
135@code{with-output-to-port}. The global output port needs to be reset to
136its previous value when @code{with-output-to-port} returns normally or
137when it is exited non-locally. Likewise, the port needs to be set again
138when control enters non-locally.
139
42155d75
MV
140Scheme code can use the @code{dynamic-wind} function to arrange for
141the setting and resetting of the global state. C code could use the
86272eed 142corresponding @code{scm_internal_dynamic_wind} function, but it might
42155d75
MV
143prefer to use the @dfn{frames} concept that is more natural for C
144code.
a0e07ba4
NJ
145
146
147@node begin
148@section Evaluating a Sequence of Expressions
149
a0e07ba4
NJ
150@cindex begin
151@cindex sequencing
152@cindex expression sequencing
153
42155d75
MV
154The @code{begin} syntax is used for grouping several expressions
155together so that they are treated as if they were one expression.
156This is particularly important when syntactic expressions are used
157which only allow one expression, but the programmer wants to use more
158than one expression in that place. As an example, consider the
159conditional expression below:
a0e07ba4
NJ
160
161@lisp
162(if (> x 0)
163 (begin (display "greater") (newline)))
164@end lisp
165
166If the two calls to @code{display} and @code{newline} were not embedded
167in a @code{begin}-statement, the call to @code{newline} would get
168misinterpreted as the else-branch of the @code{if}-expression.
169
170@deffn syntax begin expr1 expr2 @dots{}
171The expression(s) are evaluated in left-to-right order and the value
172of the last expression is returned as the value of the
173@code{begin}-expression. This expression type is used when the
174expressions before the last one are evaluated for their side effects.
86272eed
MV
175
176Guile also allows the expression @code{(begin)}, a @code{begin} with no
177sub-expressions. Such an expression returns the `unspecified' value.
a0e07ba4
NJ
178@end deffn
179
180@node if cond case
181@section Simple Conditional Evaluation
182
a0e07ba4
NJ
183@cindex conditional evaluation
184@cindex if
185@cindex case
186@cindex cond
187
188Guile provides three syntactic constructs for conditional evaluation.
189@code{if} is the normal if-then-else expression (with an optional else
190branch), @code{cond} is a conditional expression with multiple branches
191and @code{case} branches if an expression has one of a set of constant
192values.
193
194@deffn syntax if test consequent [alternate]
195All arguments may be arbitrary expressions. First, @var{test} is
196evaluated. If it returns a true value, the expression @var{consequent}
85a9b4ed 197is evaluated and @var{alternate} is ignored. If @var{test} evaluates to
a0e07ba4
NJ
198@code{#f}, @var{alternate} is evaluated instead. The value of the
199evaluated branch (@var{consequent} or @var{alternate}) is returned as
200the value of the @code{if} expression.
201
202When @var{alternate} is omitted and the @var{test} evaluates to
203@code{#f}, the value of the expression is not specified.
204@end deffn
205
206@deffn syntax cond clause1 clause2 @dots{}
207Each @code{cond}-clause must look like this:
208
209@lisp
210(@var{test} @var{expression} @dots{})
211@end lisp
212
213where @var{test} and @var{expression} are arbitrary expression, or like
214this
215
216@lisp
86272eed 217(@var{test} => @var{expression})
a0e07ba4
NJ
218@end lisp
219
220where @var{expression} must evaluate to a procedure.
221
222The @var{test}s of the clauses are evaluated in order and as soon as one
223of them evaluates to a true values, the corresponding @var{expression}s
224are evaluated in order and the last value is returned as the value of
225the @code{cond}-expression. For the @code{=>} clause type,
226@var{expression} is evaluated and the resulting procedure is applied to
227the value of @var{test}. The result of this procedure application is
228then the result of the @code{cond}-expression.
229
86272eed
MV
230The @var{test} of the last @var{clause} may be the symbol @code{else}.
231Then, if none of the preceding @var{test}s is true, the
232@var{expression}s following the @code{else} are evaluated to produce the
233result of the @code{cond}-expression.
a0e07ba4
NJ
234@end deffn
235
236@deffn syntax case key clause1 clause2 @dots{}
237@var{key} may be any expression, the @var{clause}s must have the form
238
239@lisp
240((@var{datum1} @dots{}) @var{expr1} @var{expr2} @dots{})
241@end lisp
242
243and the last @var{clause} may have the form
244
245@lisp
246(else @var{expr1} @var{expr2} @dots{})
247@end lisp
248
249All @var{datum}s must be distinct. First, @var{key} is evaluated. The
250the result of this evaluation is compared against all @var{datum}s using
85a9b4ed 251@code{eqv?}. When this comparison succeeds, the expression(s) following
a0e07ba4
NJ
252the @var{datum} are evaluated from left to right, returning the value of
253the last expression as the result of the @code{case} expression.
254
255If the @var{key} matches no @var{datum} and there is an
256@code{else}-clause, the expressions following the @code{else} are
257evaluated. If there is no such clause, the result of the expression is
258unspecified.
259@end deffn
260
261
262@node and or
263@section Conditional Evaluation of a Sequence of Expressions
264
86272eed
MV
265@code{and} and @code{or} evaluate all their arguments in order, similar
266to @code{begin}, but evaluation stops as soon as one of the expressions
a0e07ba4
NJ
267evaluates to false or true, respectively.
268
269@deffn syntax and expr @dots{}
270Evaluate the @var{expr}s from left to right and stop evaluation as soon
271as one expression evaluates to @code{#f}; the remaining expressions are
272not evaluated. The value of the last evaluated expression is returned.
273If no expression evaluates to @code{#f}, the value of the last
274expression is returned.
275
276If used without expressions, @code{#t} is returned.
277@end deffn
278
279@deffn syntax or expr @dots{}
280Evaluate the @var{expr}s from left to right and stop evaluation as soon
281as one expression evaluates to a true value (that is, a value different
282from @code{#f}); the remaining expressions are not evaluated. The value
283of the last evaluated expression is returned. If all expressions
284evaluate to @code{#f}, @code{#f} is returned.
285
286If used without expressions, @code{#f} is returned.
287@end deffn
288
289
290@node while do
291@section Iteration mechanisms
292
a0e07ba4
NJ
293@cindex iteration
294@cindex looping
295@cindex named let
296
297Scheme has only few iteration mechanisms, mainly because iteration in
298Scheme programs is normally expressed using recursion. Nevertheless,
299R5RS defines a construct for programming loops, calling @code{do}. In
300addition, Guile has an explicit looping syntax called @code{while}.
301
302@deffn syntax do ((variable1 init1 step1) @dots{}) (test expr @dots{}) command @dots{}
303The @var{init} expressions are evaluated and the @var{variables} are
304bound to their values. Then looping starts with testing the @var{test}
305expression. If @var{test} evaluates to a true value, the @var{expr}
306following the @var{test} are evaluated and the value of the last
307@var{expr} is returned as the value of the @code{do} expression. If
308@var{test} evaluates to false, the @var{command}s are evaluated in
309order, the @var{step}s are evaluated and stored into the @var{variables}
310and the next iteration starts.
311
312Any of the @var{step} expressions may be omitted, so that the
313corresponding variable is not changed during looping.
314@end deffn
315
316@deffn syntax while cond body @dots{}
bbdbcf35
KR
317Run a loop executing the @var{body} forms while @var{cond} is true.
318@var{cond} is tested at the start of each iteration, so if it's
319@code{#f} the first time then @var{body} is not executed at all. The
320return value is unspecified.
321
322Within @code{while}, two extra bindings are provided, they can be used
323from both @var{cond} and @var{body}.
324
325@deffn {Scheme Procedure} break
326Break out of the @code{while} form.
327@end deffn
328
329@deffn {Scheme Procedure} continue
330Abandon the current iteration, go back to the start and test
331@var{cond} again, etc.
332@end deffn
333
334Each @code{while} form gets its own @code{break} and @code{continue}
335procedures, operating on that @code{while}. This means when loops are
336nested the outer @code{break} can be used to escape all the way out.
337For example,
338
339@example
340(while (test1)
341 (let ((outer-break break))
342 (while (test2)
343 (if (something)
344 (outer-break #f))
345 ...)))
346@end example
347
348Note that each @code{break} and @code{continue} procedure can only be
349used within the dynamic extent of its @code{while}. Outside the
350@code{while} their behaviour is unspecified.
a0e07ba4
NJ
351@end deffn
352
353@cindex named let
354Another very common way of expressing iteration in Scheme programs is
355the use of the so-called @dfn{named let}.
356
357Named let is a variant of @code{let} which creates a procedure and calls
358it in one step. Because of the newly created procedure, named let is
359more powerful than @code{do}--it can be used for iteration, but also
360for arbitrary recursion.
361
362@deffn syntax let variable bindings body
363For the definition of @var{bindings} see the documentation about
364@code{let} (@pxref{Local Bindings}).
365
366Named @code{let} works as follows:
367
368@itemize @bullet
369@item
370A new procedure which accepts as many arguments as are in @var{bindings}
371is created and bound locally (using @code{let}) to @var{variable}. The
372new procedure's formal argument names are the name of the
373@var{variables}.
374
375@item
376The @var{body} expressions are inserted into the newly created procedure.
377
378@item
379The procedure is called with the @var{init} expressions as the formal
380arguments.
381@end itemize
382
383The next example implements a loop which iterates (by recursion) 1000
384times.
385
386@lisp
387(let lp ((x 1000))
388 (if (positive? x)
389 (lp (- x 1))
390 x))
391@result{}
3920
393@end lisp
394@end deffn
395
396
397@node Continuations
398@section Continuations
807a30f1 399@cindex continuations
a0e07ba4 400
807a30f1
KR
401A ``continuation'' is the code that will execute when a given function
402or expression returns. For example, consider
403
404@example
405(define (foo)
406 (display "hello\n")
407 (display (bar)) (newline)
408 (exit))
409@end example
410
411The continuation from the call to @code{bar} comprises a
412@code{display} of the value returned, a @code{newline} and an
413@code{exit}. This can be expressed as a function of one argument.
414
415@example
416(lambda (r)
417 (display r) (newline)
418 (exit))
419@end example
420
421In Scheme, continuations are represented as special procedures just
422like this. The special property is that when a continuation is called
423it abandons the current program location and jumps directly to that
424represented by the continuation.
425
426A continuation is like a dynamic label, capturing at run-time a point
427in program execution, including all the nested calls that have lead to
428it, or rather the code that will execute when those calls return.
429
430Continuations are created with the following functions.
a0e07ba4 431
8f85c0c6 432@deffn {Scheme Procedure} call-with-current-continuation proc
807a30f1
KR
433@deffnx {Scheme Procedure} call/cc proc
434@rnindex call-with-current-continuation
435Capture the current continuation and call @code{(@var{proc}
436@var{cont})} with it. The return value is the value returned by
437@var{proc}, or when @code{(@var{cont} @var{value})} is later invoked,
438the return is the @var{value} passed.
439
440Normally @var{cont} should be called with one argument, but when the
441location resumed is expecting multiple values (@pxref{Multiple
442Values}) then they should be passed as multiple arguments, for
443instance @code{(@var{cont} @var{x} @var{y} @var{z})}.
444
445@var{cont} may only be used from the dynamic root in which it was
446created (@pxref{Dynamic Roots}), and in a multi-threaded program only
447from the thread in which it was created, since each thread is a
448separate dynamic root.
449
86272eed
MV
450The call to @var{proc} is not part of the continuation captured, it runs
451only when the continuation is created. Often a program will want to
452store @var{cont} somewhere for later use; this can be done in
807a30f1
KR
453@var{proc}.
454
455The @code{call} in the name @code{call-with-current-continuation}
456refers to the way a call to @var{proc} gives the newly created
457continuation. It's not related to the way a call is used later to
458invoke that continuation.
459
460@code{call/cc} is an alias for @code{call-with-current-continuation}.
461This is in common use since the latter is rather long.
a0e07ba4
NJ
462@end deffn
463
807a30f1
KR
464@deftypefn {C Function} SCM scm_make_continuation (int *first)
465Capture the current continuation as described above. The return value
466is the new continuation, and @var{*first} is set to 1.
467
468When the continuation is invoked, @code{scm_make_continuation} will
469return again, this time returning the value (or set of multiple
470values) passed in that invocation, and with @var{*first} set to 0.
471@end deftypefn
472
473@sp 1
474@noindent
475Here is a simple example,
476
477@example
a0e07ba4 478(define kont #f)
807a30f1
KR
479(format #t "the return is ~a\n"
480 (call/cc (lambda (k)
481 (set! kont k)
482 1)))
483@result{} the return is 1
a0e07ba4
NJ
484
485(kont 2)
807a30f1
KR
486@result{} the return is 2
487@end example
488
489@code{call/cc} captures a continuation in which the value returned is
490going to be displayed by @code{format}. The @code{lambda} stores this
491in @code{kont} and gives an initial return @code{1} which is
492displayed. The later invocation of @code{kont} resumes the captured
493point, but this time returning @code{2}, which is displayed.
494
495When Guile is run interactively, a call to @code{format} like this has
496an implicit return back to the read-eval-print loop. @code{call/cc}
497captures that like any other return, which is why interactively
498@code{kont} will come back to read more input.
499
500@sp 1
501C programmers may note that @code{call/cc} is like @code{setjmp} in
502the way it records at runtime a point in program execution. A call to
503a continuation is like a @code{longjmp} in that it abandons the
504present location and goes to the recorded one. Like @code{longjmp},
505the value passed to the continuation is the value returned by
506@code{call/cc} on resuming there. However @code{longjmp} can only go
507up the program stack, but the continuation mechanism can go anywhere.
508
509When a continuation is invoked, @code{call/cc} and subsequent code
510effectively ``returns'' a second time. It can be confusing to imagine
511a function returning more times than it was called. It may help
512instead to think of it being stealthily re-entered and then program
513flow going on as normal.
514
86272eed
MV
515The functions @code{dynamic-wind} (@pxref{Dynamic Wind}) can be used to
516ensure setup and cleanup code is run when a program locus is resumed or
e911f3ff
MV
517abandoned through the continuation mechanism. C code can use
518@dfn{frames} (@pxref{Frames}).
807a30f1
KR
519
520@sp 1
521Continuations are a powerful mechanism, and can be used to implement
522almost any sort of control structure, such as loops, coroutines, or
523exception handlers.
524
525However the implementation of continuations in Guile is not as
526efficient as one might hope, because Guile is designed to cooperate
527with programs written in other languages, such as C, which do not know
528about continuations. Basically continuations are captured by a block
529copy of the stack, and resumed by copying back.
530
531For this reason, generally continuations should be used only when
532there is no other simple way to achieve the desired result, or when
533the elegance of the continuation mechanism outweighs the need for
534performance.
535
536Escapes upwards from loops or nested functions are generally best
537handled with exceptions (@pxref{Exceptions}). Coroutines can be
538efficiently implemented with cooperating threads (a thread holds a
539full program stack but doesn't copy it around the way continuations
540do).
a0e07ba4
NJ
541
542
543@node Multiple Values
544@section Returning and Accepting Multiple Values
545
a0e07ba4
NJ
546@cindex multiple values
547@cindex receive
548
549Scheme allows a procedure to return more than one value to its caller.
550This is quite different to other languages which only allow
551single-value returns. Returning multiple values is different from
552returning a list (or pair or vector) of values to the caller, because
85a9b4ed 553conceptually not @emph{one} compound object is returned, but several
a0e07ba4
NJ
554distinct values.
555
556The primitive procedures for handling multiple values are @code{values}
557and @code{call-with-values}. @code{values} is used for returning
558multiple values from a procedure. This is done by placing a call to
559@code{values} with zero or more arguments in tail position in a
560procedure body. @code{call-with-values} combines a procedure returning
561multiple values with a procedure which accepts these values as
562parameters.
563
564@rnindex values
d61d8580 565@deffn {Scheme Procedure} values arg1 @dots{} argN
8f85c0c6 566@deffnx {C Function} scm_values (args)
a0e07ba4
NJ
567Delivers all of its arguments to its continuation. Except for
568continuations created by the @code{call-with-values} procedure,
569all continuations take exactly one value. The effect of
570passing no value or more than one value to continuations that
571were not created by @code{call-with-values} is unspecified.
d61d8580
KR
572
573For @code{scm_values}, @var{args} is a list of arguments and the
574return is a multiple-values object which the caller can return. In
575the current implementation that object shares structure with
576@var{args}, so @var{args} should not be modified subsequently.
a0e07ba4
NJ
577@end deffn
578
579@rnindex call-with-values
8f85c0c6 580@deffn {Scheme Procedure} call-with-values producer consumer
a0e07ba4
NJ
581Calls its @var{producer} argument with no values and a
582continuation that, when passed some values, calls the
583@var{consumer} procedure with those values as arguments. The
584continuation for the call to @var{consumer} is the continuation
585of the call to @code{call-with-values}.
586
587@example
588(call-with-values (lambda () (values 4 5))
589 (lambda (a b) b))
54148bb8 590@result{} 5
a0e07ba4
NJ
591
592@end example
593@example
54148bb8
KR
594(call-with-values * -)
595@result{} -1
a0e07ba4
NJ
596@end example
597@end deffn
598
599In addition to the fundamental procedures described above, Guile has a
600module which exports a syntax called @code{receive}, which is much more
601convenient. If you want to use it in your programs, you have to load
602the module @code{(ice-9 receive)} with the statement
603
604@lisp
605(use-modules (ice-9 receive))
606@end lisp
607
608@deffn {library syntax} receive formals expr body @dots{}
609Evaluate the expression @var{expr}, and bind the result values (zero or
610more) to the formal arguments in the formal argument list @var{formals}.
611@var{formals} must have the same syntax like the formal argument list
612used in @code{lambda} (@pxref{Lambda}). After binding the variables,
613the expressions in @var{body} @dots{} are evaluated in order.
614@end deffn
615
616
617@node Exceptions
618@section Exceptions
619@cindex error handling
620@cindex exception handling
621
622A common requirement in applications is to want to jump
623@dfn{non-locally} from the depths of a computation back to, say, the
624application's main processing loop. Usually, the place that is the
625target of the jump is somewhere in the calling stack of procedures that
626called the procedure that wants to jump back. For example, typical
627logic for a key press driven application might look something like this:
628
629@example
630main-loop:
631 read the next key press and call dispatch-key
632
633dispatch-key:
634 lookup the key in a keymap and call an appropriate procedure,
635 say find-file
636
637find-file:
638 interactively read the required file name, then call
639 find-specified-file
640
641find-specified-file:
642 check whether file exists; if not, jump back to main-loop
643 @dots{}
644@end example
645
646The jump back to @code{main-loop} could be achieved by returning through
647the stack one procedure at a time, using the return value of each
648procedure to indicate the error condition, but Guile (like most modern
649programming languages) provides an additional mechanism called
650@dfn{exception handling} that can be used to implement such jumps much
651more conveniently.
652
653@menu
654* Exception Terminology:: Different ways to say the same thing.
655* Catch:: Setting up to catch exceptions.
656* Throw:: Throwing an exception.
657* Lazy Catch:: Catch without unwinding the stack.
658* Exception Implementation:: How Guile implements exceptions.
659@end menu
660
661
662@node Exception Terminology
663@subsection Exception Terminology
664
665There are several variations on the terminology for dealing with
666non-local jumps. It is useful to be aware of them, and to realize
667that they all refer to the same basic mechanism.
668
669@itemize @bullet
670@item
671Actually making a non-local jump may be called @dfn{raising an
672exception}, @dfn{raising a signal}, @dfn{throwing an exception} or
673@dfn{doing a long jump}. When the jump indicates an error condition,
674people may talk about @dfn{signalling}, @dfn{raising} or @dfn{throwing}
675@dfn{an error}.
676
677@item
678Handling the jump at its target may be referred to as @dfn{catching} or
679@dfn{handling} the @dfn{exception}, @dfn{signal} or, where an error
680condition is involved, @dfn{error}.
681@end itemize
682
683Where @dfn{signal} and @dfn{signalling} are used, special care is needed
86272eed 684to avoid the risk of confusion with POSIX signals.
a0e07ba4
NJ
685
686This manual prefers to speak of throwing and catching exceptions, since
687this terminology matches the corresponding Guile primitives.
688
689
690@node Catch
691@subsection Catching Exceptions
692
693@code{catch} is used to set up a target for a possible non-local jump.
694The arguments of a @code{catch} expression are a @dfn{key}, which
695restricts the set of exceptions to which this @code{catch} applies, a
86272eed
MV
696thunk that specifies the code to execute and a @dfn{handler} procedure
697that says what to do if an exception is thrown while executing the code.
698Note that if the execution thunk executes @dfn{normally}, which means
699without throwing any exceptions, the handler procedure is not called at
700all.
a0e07ba4 701
86272eed 702When an exception is thrown using the @code{throw} function, the first
a0e07ba4
NJ
703argument of the @code{throw} is a symbol that indicates the type of the
704exception. For example, Guile throws an exception using the symbol
705@code{numerical-overflow} to indicate numerical overflow errors such as
706division by zero:
707
708@lisp
709(/ 1 0)
710@result{}
711ABORT: (numerical-overflow)
712@end lisp
713
714The @var{key} argument in a @code{catch} expression corresponds to this
715symbol. @var{key} may be a specific symbol, such as
716@code{numerical-overflow}, in which case the @code{catch} applies
717specifically to exceptions of that type; or it may be @code{#t}, which
718means that the @code{catch} applies to all exceptions, irrespective of
719their type.
720
721The second argument of a @code{catch} expression should be a thunk
722(i.e. a procedure that accepts no arguments) that specifies the normal
723case code. The @code{catch} is active for the execution of this thunk,
724including any code called directly or indirectly by the thunk's body.
725Evaluation of the @code{catch} expression activates the catch and then
726calls this thunk.
727
728The third argument of a @code{catch} expression is a handler procedure.
729If an exception is thrown, this procedure is called with exactly the
730arguments specified by the @code{throw}. Therefore, the handler
731procedure must be designed to accept a number of arguments that
732corresponds to the number of arguments in all @code{throw} expressions
733that can be caught by this @code{catch}.
734
8f85c0c6
NJ
735@deffn {Scheme Procedure} catch key thunk handler
736@deffnx {C Function} scm_catch (key, thunk, handler)
a0e07ba4
NJ
737Invoke @var{thunk} in the dynamic context of @var{handler} for
738exceptions matching @var{key}. If thunk throws to the symbol
739@var{key}, then @var{handler} is invoked this way:
740@lisp
741(handler key args ...)
742@end lisp
743
744@var{key} is a symbol or @code{#t}.
745
746@var{thunk} takes no arguments. If @var{thunk} returns
747normally, that is the return value of @code{catch}.
748
749Handler is invoked outside the scope of its own @code{catch}.
750If @var{handler} again throws to the same key, a new handler
751from further up the call chain is invoked.
752
753If the key is @code{#t}, then a throw to @emph{any} symbol will
754match this call to @code{catch}.
755@end deffn
756
757If the handler procedure needs to match a variety of @code{throw}
758expressions with varying numbers of arguments, you should write it like
759this:
760
761@lisp
762(lambda (key . args)
763 @dots{})
764@end lisp
765
766@noindent
767The @var{key} argument is guaranteed always to be present, because a
768@code{throw} without a @var{key} is not valid. The number and
769interpretation of the @var{args} varies from one type of exception to
770another, but should be specified by the documentation for each exception
771type.
772
773Note that, once the handler procedure is invoked, the catch that led to
774the handler procedure being called is no longer active. Therefore, if
775the handler procedure itself throws an exception, that exception can
776only be caught by another active catch higher up the call stack, if
777there is one.
778
53872505
KR
779@sp 1
780@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)
781The above @code{scm_catch} takes Scheme procedures as body and handler
782arguments. @code{scm_internal_catch} is an equivalent taking C
783functions.
784
785@var{body} is called as @code{@var{body} (@var{body_data})} with a
786catch on exceptions of the given @var{tag} type. If an exception is
787caught, @var{handler} is called @code{@var{handler}
788(@var{handler_data}, @var{key}, @var{args})}. @var{key} and
789@var{args} are the @code{SCM} key and argument list from the
790@code{throw}.
791
792@tpindex scm_t_catch_body
793@tpindex scm_t_catch_handler
794@var{body} and @var{handler} should have the following prototypes.
795@code{scm_t_catch_body} and @code{scm_t_catch_handler} are pointer
796typedefs for these.
797
798@example
799SCM body (void *data);
800SCM handler (void *data, SCM key, SCM args);
801@end example
802
803The @var{body_data} and @var{handler_data} parameters are passed to
804the respective calls so an application can communicate extra
805information to those functions.
806
807If the data consists of an @code{SCM} object, care should be taken
808that it isn't garbage collected while still required. If the
809@code{SCM} is a local C variable, one way to protect it is to pass a
810pointer to that variable as the data parameter, since the C compiler
811will then know the value must be held on the stack. Another way is to
812use @code{scm_remember_upto_here_1} (@pxref{Remembering During
813Operations}).
814@end deftypefn
815
a0e07ba4
NJ
816
817@node Throw
818@subsection Throwing Exceptions
819
820The @code{throw} primitive is used to throw an exception. One argument,
821the @var{key}, is mandatory, and must be a symbol; it indicates the type
822of exception that is being thrown. Following the @var{key},
823@code{throw} accepts any number of additional arguments, whose meaning
824depends on the exception type. The documentation for each possible type
825of exception should specify the additional arguments that are expected
826for that kind of exception.
827
8f85c0c6
NJ
828@deffn {Scheme Procedure} throw key . args
829@deffnx {C Function} scm_throw (key, args)
a0e07ba4
NJ
830Invoke the catch form matching @var{key}, passing @var{args} to the
831@var{handler}.
832
833@var{key} is a symbol. It will match catches of the same symbol or of
834@code{#t}.
835
836If there is no handler at all, Guile prints an error and then exits.
837@end deffn
838
839When an exception is thrown, it will be caught by the innermost
840@code{catch} expression that applies to the type of the thrown
841exception; in other words, the innermost @code{catch} whose @var{key} is
842@code{#t} or is the same symbol as that used in the @code{throw}
843expression. Once Guile has identified the appropriate @code{catch}, it
844handles the exception by applying that @code{catch} expression's handler
845procedure to the arguments of the @code{throw}.
846
847If there is no appropriate @code{catch} for a thrown exception, Guile
848prints an error to the current error port indicating an uncaught
849exception, and then exits. In practice, it is quite difficult to
850observe this behaviour, because Guile when used interactively installs a
851top level @code{catch} handler that will catch all exceptions and print
852an appropriate error message @emph{without} exiting. For example, this
853is what happens if you try to throw an unhandled exception in the
854standard Guile REPL; note that Guile's command loop continues after the
855error message:
856
857@lisp
858guile> (throw 'badex)
859<unnamed port>:3:1: In procedure gsubr-apply @dots{}
860<unnamed port>:3:1: unhandled-exception: badex
861ABORT: (misc-error)
862guile>
863@end lisp
864
865The default uncaught exception behaviour can be observed by evaluating a
866@code{throw} expression from the shell command line:
867
868@example
869$ guile -c "(begin (throw 'badex) (display \"here\\n\"))"
870guile: uncaught throw to badex: ()
871$
872@end example
873
874@noindent
875That Guile exits immediately following the uncaught exception
876is shown by the absence of any output from the @code{display}
877expression, because Guile never gets to the point of evaluating that
878expression.
879
880
881@node Lazy Catch
882@subsection Catch Without Unwinding
883
884A @dfn{lazy catch} is used in the same way as a normal @code{catch},
885with @var{key}, @var{thunk} and @var{handler} arguments specifying the
886exception type, normal case code and handler procedure, but differs in
887one important respect: the handler procedure is executed without
888unwinding the call stack from the context of the @code{throw} expression
889that caused the handler to be invoked.
890
8f85c0c6
NJ
891@deffn {Scheme Procedure} lazy-catch key thunk handler
892@deffnx {C Function} scm_lazy_catch (key, thunk, handler)
a0e07ba4
NJ
893This behaves exactly like @code{catch}, except that it does
894not unwind the stack before invoking @var{handler}.
895The @var{handler} procedure is not allowed to return:
896it must throw to another catch, or otherwise exit non-locally.
897@end deffn
898
53872505
KR
899@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)
900The above @code{scm_lazy_catch} takes Scheme procedures as body and
901handler arguments. @code{scm_internal_lazy_catch} is an equivalent
902taking C functions. See @code{scm_internal_catch} (@pxref{Catch}) for
903a description of the parameters, the behaviour however of course
904follows @code{lazy-catch}.
905@end deftypefn
906
a0e07ba4
NJ
907Typically, @var{handler} should save any desired state associated with
908the stack at the point where the corresponding @code{throw} occurred,
909and then throw an exception itself --- usually the same exception as the
910one it caught. If @var{handler} is invoked and does @emph{not} throw an
911exception, Guile itself throws an exception with key @code{misc-error}.
912
913Not unwinding the stack means that throwing an exception that is caught
914by a @code{lazy-catch} is @emph{almost} equivalent to calling the
915@code{lazy-catch}'s handler inline instead of each @code{throw}, and
916then omitting the surrounding @code{lazy-catch}. In other words,
917
918@lisp
919(lazy-catch 'key
920 (lambda () @dots{} (throw 'key args @dots{}) @dots{})
921 handler)
922@end lisp
923
924@noindent
925is @emph{almost} equivalent to
926
927@lisp
928((lambda () @dots{} (handler 'key args @dots{}) @dots{}))
929@end lisp
930
931@noindent
932But why only @emph{almost}? The difference is that with
933@code{lazy-catch} (as with normal @code{catch}), the dynamic context is
934unwound back to just outside the @code{lazy-catch} expression before
935invoking the handler. (For an introduction to what is meant by dynamic
936context, @xref{Dynamic Wind}.)
937
938Then, when the handler @emph{itself} throws an exception, that exception
939must be caught by some kind of @code{catch} (including perhaps another
940@code{lazy-catch}) higher up the call stack.
941
942The dynamic context also includes @code{with-fluids} blocks (REFFIXME),
943so the effect of unwinding the dynamic context can also be seen in fluid
944variable values. This is illustrated by the following code, in which
945the normal case thunk uses @code{with-fluids} to temporarily change the
946value of a fluid:
947
948@lisp
949(define f (make-fluid))
950(fluid-set! f "top level value")
951
952(define (handler . args)
953 (cons (fluid-ref f) args))
954
955(lazy-catch 'foo
956 (lambda ()
957 (with-fluids ((f "local value"))
958 (throw 'foo)))
959 handler)
960@result{}
961("top level value" foo)
962
963((lambda ()
964 (with-fluids ((f "local value"))
965 (handler 'foo))))
966@result{}
967("local value" foo)
968@end lisp
969
970@noindent
971In the @code{lazy-catch} version, the unwinding of dynamic context
972restores @code{f} to its value outside the @code{with-fluids} block
973before the handler is invoked, so the handler's @code{(fluid-ref f)}
974returns the external value.
975
976@code{lazy-catch} is useful because it permits the implementation of
977debuggers and other reflective programming tools that need to access the
978state of the call stack at the exact point where an exception or an
979error is thrown. For an example of this, see REFFIXME:stack-catch.
980
981
982@node Exception Implementation
983@subsection How Guile Implements Exceptions
984
985It is traditional in Scheme to implement exception systems using
986@code{call-with-current-continuation}. Continuations
987(@pxref{Continuations}) are such a powerful concept that any other
988control mechanism --- including @code{catch} and @code{throw} --- can be
989implemented in terms of them.
990
991Guile does not implement @code{catch} and @code{throw} like this,
992though. Why not? Because Guile is specifically designed to be easy to
993integrate with applications written in C. In a mixed Scheme/C
994environment, the concept of @dfn{continuation} must logically include
995``what happens next'' in the C parts of the application as well as the
996Scheme parts, and it turns out that the only reasonable way of
997implementing continuations like this is to save and restore the complete
998C stack.
999
1000So Guile's implementation of @code{call-with-current-continuation} is a
1001stack copying one. This allows it to interact well with ordinary C
1002code, but means that creating and calling a continuation is slowed down
1003by the time that it takes to copy the C stack.
1004
1005The more targeted mechanism provided by @code{catch} and @code{throw}
1006does not need to save and restore the C stack because the @code{throw}
1007always jumps to a location higher up the stack of the code that executes
1008the @code{throw}. Therefore Guile implements the @code{catch} and
1009@code{throw} primitives independently of
1010@code{call-with-current-continuation}, in a way that takes advantage of
1011this @emph{upwards only} nature of exceptions.
1012
1013
1014@node Error Reporting
1015@section Procedures for Signaling Errors
1016
1017Guile provides a set of convenience procedures for signaling error
1018conditions that are implemented on top of the exception primitives just
1019described.
1020
8f85c0c6 1021@deffn {Scheme Procedure} error msg args @dots{}
a0e07ba4
NJ
1022Raise an error with key @code{misc-error} and a message constructed by
1023displaying @var{msg} and writing @var{args}.
1024@end deffn
1025
8f85c0c6
NJ
1026@deffn {Scheme Procedure} scm-error key subr message args data
1027@deffnx {C Function} scm_error_scm (key, subr, message, args, data)
a0e07ba4
NJ
1028Raise an error with key @var{key}. @var{subr} can be a string
1029naming the procedure associated with the error, or @code{#f}.
1030@var{message} is the error message string, possibly containing
1031@code{~S} and @code{~A} escapes. When an error is reported,
1032these are replaced by formatting the corresponding members of
1033@var{args}: @code{~A} (was @code{%s} in older versions of
1034Guile) formats using @code{display} and @code{~S} (was
1035@code{%S}) formats using @code{write}. @var{data} is a list or
1036@code{#f} depending on @var{key}: if @var{key} is
1037@code{system-error} then it should be a list containing the
1038Unix @code{errno} value; If @var{key} is @code{signal} then it
1039should be a list containing the Unix signal number; otherwise
1040it will usually be @code{#f}.
1041@end deffn
1042
8f85c0c6
NJ
1043@deffn {Scheme Procedure} strerror err
1044@deffnx {C Function} scm_strerror (err)
a0e07ba4
NJ
1045Return the Unix error message corresponding to @var{err}, which
1046must be an integer value.
1047@end deffn
1048
1049@c begin (scm-doc-string "boot-9.scm" "false-if-exception")
1050@deffn syntax false-if-exception expr
1051Returns the result of evaluating its argument; however
1052if an exception occurs then @code{#f} is returned instead.
1053@end deffn
1054@c end
1055
1056
1057@node Dynamic Wind
1058@section Dynamic Wind
1059
a0e07ba4 1060@rnindex dynamic-wind
8f85c0c6
NJ
1061@deffn {Scheme Procedure} dynamic-wind in_guard thunk out_guard
1062@deffnx {C Function} scm_dynamic_wind (in_guard, thunk, out_guard)
a0e07ba4
NJ
1063All three arguments must be 0-argument procedures.
1064@var{in_guard} is called, then @var{thunk}, then
1065@var{out_guard}.
1066
1067If, any time during the execution of @var{thunk}, the
86272eed
MV
1068dynamic extent of the @code{dynamic-wind} expression is escaped
1069non-locally, @var{out_guard} is called. If the dynamic extent of
a0e07ba4
NJ
1070the dynamic-wind is re-entered, @var{in_guard} is called. Thus
1071@var{in_guard} and @var{out_guard} may be called any number of
1072times.
1073@lisp
1074(define x 'normal-binding)
1075@result{} x
1076(define a-cont (call-with-current-continuation
54148bb8
KR
1077 (lambda (escape)
1078 (let ((old-x x))
1079 (dynamic-wind
1080 ;; in-guard:
1081 ;;
1082 (lambda () (set! x 'special-binding))
1083
1084 ;; thunk
1085 ;;
1086 (lambda () (display x) (newline)
1087 (call-with-current-continuation escape)
1088 (display x) (newline)
1089 x)
1090
1091 ;; out-guard:
1092 ;;
1093 (lambda () (set! x old-x)))))))
a0e07ba4
NJ
1094
1095;; Prints:
1096special-binding
1097;; Evaluates to:
1098@result{} a-cont
1099x
1100@result{} normal-binding
1101(a-cont #f)
1102;; Prints:
1103special-binding
1104;; Evaluates to:
1105@result{} a-cont ;; the value of the (define a-cont...)
1106x
1107@result{} normal-binding
1108a-cont
1109@result{} special-binding
1110@end lisp
1111@end deffn
9401323e 1112
86272eed
MV
1113@node Frames
1114@section Frames
1115
1116For Scheme code, the fundamental procedure to react to non-local entry
1117and exits of dynamic contexts is @code{dynamic-wind}. C code could use
1118@code{scm_internal_dynamic_wind}, but since C does not allow the
1119convenient construction of anonymous procedures that close over lexical
1120variables, this will be, well, inconvenient. Instead, C code can use
1121@dfn{frames}.
1122
6394add1
MV
1123Guile offers the functions @code{scm_frame_begin} and
1124@code{scm_frame_end} to delimit a dynamic extent. Within this dynamic
86272eed
MV
1125extent, which is called a @dfn{frame}, you can perform various
1126@dfn{frame actions} that control what happens when the frame is entered
1127or left. For example, you can register a cleanup routine with
6394add1 1128@code{scm_frame_unwind} that is executed when the frame is left. There are
86272eed
MV
1129several other more specialized frame actions as well, for example to
1130temporarily block the execution of asyncs or to temporarily change the
1131current output port. They are described elsewhere in this manual.
1132
1133Here is an example that shows how to prevent memory leaks.
1134
1135@example
1136
1137/* Suppose there is a function called FOO in some library that you
1138 would like to make available to Scheme code (or to C code that
1139 follows the Scheme conventions).
1140
1141 FOO takes two C strings and returns a new string. When an error has
1142 occurred in FOO, it returns NULL.
1143*/
1144
1145char *foo (char *s1, char *s2);
1146
1147/* SCM_FOO interfaces the C function FOO to the Scheme way of life.
1148 It takes care to free up all temporary strings in the case of
1149 non-local exits.
1150
1151 It uses SCM_TO_STRING as a helper procedure.
1152 */
1153
1154char *
1155scm_to_string (SCM obj)
1156@{
1157 if (SCM_STRINGP (obj))
1158 @{
1159 char *res = scm_malloc (SCM_STRING_LENGTH (obj)+1);
1160 strcpy (res, SCM_STRING_CHARS (obj));
1161 scm_remember_upto_here_1 (obj);
1162 return res;
1163 @}
1164 else
1165 scm_wrong_type_arg ("scm_to_string", 1, obj);
1166@}
1167
1168SCM
1169scm_foo (SCM s1, SCM s2)
1170@{
1171 char *c_s1, *c_s2, *c_res;
1172
6394add1 1173 scm_frame_begin (0);
86272eed
MV
1174
1175 c_s1 = scm_to_string (s1);
f1da8e4e 1176 scm_frame_unwind_handler (free, c_s1, SCM_F_WIND_EXPLICITLY);
86272eed
MV
1177
1178 c_s2 = scm_to_string (s2);
f1da8e4e 1179 scm_frame_unwind_handler (free, c_s2, SCM_F_WIND_EXPLICITLY);
86272eed
MV
1180
1181 c_res = foo (c_s1, c_s2);
1182 if (c_res == NULL)
1183 scm_memory_error ("foo");
1184
6394add1 1185 scm_frame_end ();
86272eed
MV
1186
1187 return scm_take0str (res);
1188@}
1189@end example
1190
1191@deftp {C Type} scm_t_frame_flags
1192This is an enumeration of several flags that modify the behavior of
1193@code{scm_begin_frame}. The flags are listed in the following table.
1194
1195@table @code
1196@item SCM_F_FRAME_REWINDABLE
1197The frame is @dfn{rewindable}. This means that it can be reentered
1198non-locally (via the invokation of a continuation). The default is that
1199a frame can not be reentered non-locally.
1200@end table
1201
1202@end deftp
1203
6394add1 1204@deftypefn {C Function} void scm_frame_begin (scm_t_frame_flags flags)
86272eed
MV
1205The function @code{scm_begin_frame} starts a new frame and makes it the
1206`current' one.
1207
1208The @var{flags} argument determines the default behavior of the frame.
1209For normal frames, use 0. This will result in a frame that can not be
1210reentered with a captured continuation. When you are prepared to handle
1211reentries, include @code{SCM_F_FRAME_REWINDABLE} in @var{flags}.
1212
42155d75
MV
1213Being prepared for reentry means that the effects of unwind handlers
1214can be undone on reentry. In the example above, we want to prevent a
1215memory leak on non-local exit and thus register an unwind handler that
1216frees the memory. But once the memory is freed, we can not get it
1217back on reentry. Thus reentry can not be allowed.
1218
1219The consequence is that continuations become less useful when
1220non-reenterable frames are captured, but you don't need to worry about
1221that too much.
1222
86272eed
MV
1223The frame is ended either implicitly when a non-local exit happens, or
1224explicitly with @code{scm_end_frame}. You must make sure that a frame
42155d75
MV
1225is indeed ended properly. If you fail to call @code{scm_end_frame}
1226for each @code{scm_begin_frame}, the behavior is undefined.
86272eed
MV
1227@end deftypefn
1228
6394add1 1229@deftypefn {C Function} void scm_frame_end ()
86272eed
MV
1230End the current frame explicitly and make the previous frame current.
1231@end deftypefn
1232
1233@deftp {C Type} scm_t_wind_flags
1234This is an enumeration of several flags that modify the behavior of
f1da8e4e
MV
1235@code{scm_on_unwind_handler} and @code{scm_on_rewind_handler}. The
1236flags are listed in the following table.
86272eed
MV
1237
1238@table @code
becc4b27 1239@item SCM_F_WIND_EXPLICITLY
86272eed
MV
1240The registered action is also carried out when the frame is entered or
1241left locally.
1242@end table
1243@end deftp
1244
f1da8e4e
MV
1245@deftypefn {C Function} void scm_frame_unwind_handler (void (*func)(void *), void *data, scm_t_wind_flags flags)
1246@deftypefnx {C Function} void scm_frame_unwind_handler_with_scm (void (*func)(SCM), SCM data, scm_t_wind_flags flags)
86272eed
MV
1247Arranges for @var{func} to be called with @var{data} as its arguments
1248when the current frame ends implicitly. If @var{flags} contains
becc4b27 1249@code{SCM_F_WIND_EXPLICITLY}, @var{func} is also called when the frame
6394add1 1250ends explicitly with @code{scm_frame_end}.
becc4b27 1251
f1da8e4e
MV
1252The function @code{scm_frame_unwind_handler_with_scm} takes care that
1253@var{data} is protected from garbage collection.
86272eed
MV
1254@end deftypefn
1255
f1da8e4e
MV
1256@deftypefn {C Function} void scm_frame_rewind_handler (void (*func)(void *), void *data, scm_t_wind_flags flags)
1257@deftypefnx {C Function} void scm_frame_rewind_handler_with_scm (void (*func)(SCM), SCM data, scm_t_wind_flags flags)
86272eed
MV
1258Arrange for @var{func} to be called with @var{data} as its argument when
1259the current frame is restarted by rewinding the stack. When @var{flags}
becc4b27 1260contains @code{SCM_F_WIND_EXPLICITLY}, @var{func} is called immediately
86272eed 1261as well.
becc4b27 1262
f1da8e4e
MV
1263The function @code{scm_frame_rewind_handler_with_scm} takes care that
1264@var{data} is protected from garbage collection.
86272eed
MV
1265@end deftypefn
1266
9401323e
NJ
1267
1268@node Handling Errors
86272eed 1269@section How to Handle Errors
9401323e
NJ
1270
1271Error handling is based on @code{catch} and @code{throw}. Errors are
1272always thrown with a @var{key} and four arguments:
1273
1274@itemize @bullet
1275@item
1276@var{key}: a symbol which indicates the type of error. The symbols used
1277by libguile are listed below.
1278
1279@item
1280@var{subr}: the name of the procedure from which the error is thrown, or
1281@code{#f}.
1282
1283@item
1284@var{message}: a string (possibly language and system dependent)
1285describing the error. The tokens @code{~A} and @code{~S} can be
1286embedded within the message: they will be replaced with members of the
1287@var{args} list when the message is printed. @code{~A} indicates an
1288argument printed using @code{display}, while @code{~S} indicates an
1289argument printed using @code{write}. @var{message} can also be
1290@code{#f}, to allow it to be derived from the @var{key} by the error
1291handler (may be useful if the @var{key} is to be thrown from both C and
1292Scheme).
1293
1294@item
1295@var{args}: a list of arguments to be used to expand @code{~A} and
1296@code{~S} tokens in @var{message}. Can also be @code{#f} if no
1297arguments are required.
1298
1299@item
1300@var{rest}: a list of any additional objects required. e.g., when the
1301key is @code{'system-error}, this contains the C errno value. Can also
1302be @code{#f} if no additional objects are required.
1303@end itemize
1304
1305In addition to @code{catch} and @code{throw}, the following Scheme
1306facilities are available:
1307
f2ba76ae
NJ
1308@deffn {Scheme Procedure} display-error stack port subr message args rest
1309@deffnx {C Function} scm_display_error (stack, port, subr, message, args, rest)
1310Display an error message to the output port @var{port}.
1311@var{stack} is the saved stack for the error, @var{subr} is
1312the name of the procedure in which the error occurred and
1313@var{message} is the actual error message, which may contain
1314formatting instructions. These will format the arguments in
1315the list @var{args} accordingly. @var{rest} is currently
1316ignored.
1317@end deffn
1318
9401323e
NJ
1319The following are the error keys defined by libguile and the situations
1320in which they are used:
1321
1322@itemize @bullet
1323@item
43bc657a 1324@cindex @code{error-signal}
9401323e 1325@code{error-signal}: thrown after receiving an unhandled fatal signal
85a9b4ed 1326such as SIGSEGV, SIGBUS, SIGFPE etc. The @var{rest} argument in the throw
9401323e
NJ
1327contains the coded signal number (at present this is not the same as the
1328usual Unix signal number).
1329
1330@item
43bc657a 1331@cindex @code{system-error}
9401323e
NJ
1332@code{system-error}: thrown after the operating system indicates an
1333error condition. The @var{rest} argument in the throw contains the
1334errno value.
1335
1336@item
43bc657a 1337@cindex @code{numerical-overflow}
9401323e
NJ
1338@code{numerical-overflow}: numerical overflow.
1339
1340@item
43bc657a 1341@cindex @code{out-of-range}
9401323e
NJ
1342@code{out-of-range}: the arguments to a procedure do not fall within the
1343accepted domain.
1344
1345@item
43bc657a 1346@cindex @code{wrong-type-arg}
85a9b4ed 1347@code{wrong-type-arg}: an argument to a procedure has the wrong type.
9401323e
NJ
1348
1349@item
43bc657a 1350@cindex @code{wrong-number-of-args}
9401323e
NJ
1351@code{wrong-number-of-args}: a procedure was called with the wrong number
1352of arguments.
1353
1354@item
43bc657a 1355@cindex @code{memory-allocation-error}
9401323e
NJ
1356@code{memory-allocation-error}: memory allocation error.
1357
1358@item
43bc657a 1359@cindex @code{stack-overflow}
9401323e
NJ
1360@code{stack-overflow}: stack overflow error.
1361
1362@item
63226e80
KR
1363@cindex @code{regular-expression-syntax}
1364@code{regular-expression-syntax}: errors generated by the regular
1365expression library.
9401323e
NJ
1366
1367@item
43bc657a 1368@cindex @code{misc-error}
9401323e
NJ
1369@code{misc-error}: other errors.
1370@end itemize
1371
1372
1373@subsection C Support
1374
f8a6b8be 1375In the following C functions, @var{SUBR} and @var{MESSAGE} parameters
86272eed 1376can be @code{NULL} to give the effect of @code{#f} described above.
f8a6b8be
KR
1377
1378@deftypefn {C Function} SCM scm_error (SCM @var{key}, char *@var{subr}, char *@var{message}, SCM @var{args}, SCM @var{rest})
1379Throw an error, as per @code{scm-error} above.
1380@end deftypefn
1381
1382@deftypefn {C Function} void scm_syserror (char *@var{subr})
1383@deftypefnx {C Function} void scm_syserror_msg (char *@var{subr}, char *@var{message}, SCM @var{args})
1384Throw an error with key @code{system-error} and supply @code{errno} in
1385the @var{rest} argument. For @code{scm_syserror} the message is
1386generated using @code{strerror}.
1387
1388Care should be taken that any code in between the failing operation
1389and the call to these routines doesn't change @code{errno}.
1390@end deftypefn
1391
1392@deftypefn {C Function} void scm_num_overflow (char *@var{subr})
1393@deftypefnx {C Function} void scm_out_of_range (char *@var{subr}, SCM @var{bad_value})
1394@deftypefnx {C Function} void scm_wrong_num_args (SCM @var{proc})
1395@deftypefnx {C Function} void scm_wrong_type_arg (char *@var{subr}, int @var{argnum}, SCM @var{bad_value})
1396@deftypefnx {C Function} void scm_memory_error (char *@var{subr})
1397Throw an error with the various keys described above.
1398
1399For @code{scm_wrong_num_args}, @var{proc} should be a Scheme symbol
1400which is the name of the procedure incorrectly invoked.
1401@end deftypefn
9401323e 1402
9401323e 1403
a0e07ba4
NJ
1404@c Local Variables:
1405@c TeX-master: "guile.texi"
1406@c End: