2 @c This is part of the SXEmacs Lisp Reference Manual.
3 @c Copyright (C) 1990, 1991, 1992, 1993, 1994 Free Software Foundation, Inc.
4 @c Copyright (C) 2005 Sebastian Freundt <hroptatyr@sxemacs.org>
5 @c See the file lispref.texi for copying conditions.
6 @setfilename ../../info/control.info
8 @node Control Structures, Variables, Evaluation, Top
9 @chapter Control Structures
10 @cindex special forms for control structures
11 @cindex control structures
13 A Lisp program consists of expressions or @dfn{forms} (@pxref{Forms}).
14 We control the order of execution of the forms by enclosing them in
15 @dfn{control structures}. Control structures are special forms which
16 control when, whether, or how many times to execute the forms they
19 The simplest order of execution is sequential execution: first form
20 @var{a}, then form @var{b}, and so on. This is what happens when you
21 write several forms in succession in the body of a function, or at top
22 level in a file of Lisp code---the forms are executed in the order
23 written. We call this @dfn{textual order}. For example, if a function
24 body consists of two forms @var{a} and @var{b}, evaluation of the
25 function evaluates first @var{a} and then @var{b}, and the function's
26 value is the value of @var{b}.
28 Explicit control structures make possible an order of execution other
31 SXEmacs Lisp provides several kinds of control structure, including
32 other varieties of sequencing, conditionals, iteration, and (controlled)
33 jumps---all discussed below. The built-in control structures are
34 special forms since their subforms are not necessarily evaluated or not
35 evaluated sequentially. You can use macros to define your own control
36 structure constructs (@pxref{Macros}).
39 * Sequencing:: Evaluation in textual order.
40 * Conditionals:: @code{if}, @code{cond}.
41 * Combining Conditions:: @code{and}, @code{or}, @code{not}.
42 * Iteration:: @code{while} loops.
43 * Nonlocal Exits:: Jumping out of a sequence.
50 Evaluating forms in the order they appear is the most common way
51 control passes from one form to another. In some contexts, such as in a
52 function body, this happens automatically. Elsewhere you must use a
53 control structure construct to do this: @code{progn}, the simplest
54 control construct of Lisp.
56 A @code{progn} special form looks like this:
60 (progn @var{a} @var{b} @var{c} @dots{})
65 and it says to execute the forms @var{a}, @var{b}, @var{c} and so on, in
66 that order. These forms are called the body of the @code{progn} form.
67 The value of the last form in the body becomes the value of the entire
70 @cindex implicit @code{progn}
71 In the early days of Lisp, @code{progn} was the only way to execute
72 two or more forms in succession and use the value of the last of them.
73 But programmers found they often needed to use a @code{progn} in the
74 body of a function, where (at that time) only one form was allowed. So
75 the body of a function was made into an ``implicit @code{progn}'':
76 several forms are allowed just as in the body of an actual @code{progn}.
77 Many other control structures likewise contain an implicit @code{progn}.
78 As a result, @code{progn} is not used as often as it used to be. It is
79 needed now most often inside an @code{unwind-protect}, @code{and},
80 @code{or}, or in the @var{then}-part of an @code{if}.
82 @defspec progn forms@dots{}
83 This special form evaluates all of the @var{forms}, in textual
84 order, returning the result of the final form.
88 (progn (print "The first form")
89 (print "The second form")
90 (print "The third form"))
91 @print{} "The first form"
92 @print{} "The second form"
93 @print{} "The third form"
94 @result{} "The third form"
99 Two other control constructs likewise evaluate a series of forms but return
102 @defspec prog1 form1 forms@dots{}
103 This special form evaluates @var{form1} and all of the @var{forms}, in
104 textual order, returning the result of @var{form1}.
108 (prog1 (print "The first form")
109 (print "The second form")
110 (print "The third form"))
111 @print{} "The first form"
112 @print{} "The second form"
113 @print{} "The third form"
114 @result{} "The first form"
118 Here is a way to remove the first element from a list in the variable
119 @code{x}, then return the value of that former element:
122 (prog1 (car x) (setq x (cdr x)))
126 @defspec prog2 form1 form2 forms@dots{}
127 This special form evaluates @var{form1}, @var{form2}, and all of the
128 following @var{forms}, in textual order, returning the result of
133 (prog2 (print "The first form")
134 (print "The second form")
135 (print "The third form"))
136 @print{} "The first form"
137 @print{} "The second form"
138 @print{} "The third form"
139 @result{} "The second form"
146 @section Conditionals
147 @cindex conditional evaluation
149 Conditional control structures choose among alternatives. SXEmacs
150 Lisp has two conditional forms: @code{if}, which is much the same as in
151 other languages, and @code{cond}, which is a generalized case
154 @defspec if condition then-form else-forms@dots{}
155 @code{if} chooses between the @var{then-form} and the @var{else-forms}
156 based on the value of @var{condition}. If the evaluated @var{condition} is
157 non-@code{nil}, @var{then-form} is evaluated and the result returned.
158 Otherwise, the @var{else-forms} are evaluated in textual order, and the
159 value of the last one is returned. (The @var{else} part of @code{if} is
160 an example of an implicit @code{progn}. @xref{Sequencing}.)
162 If @var{condition} has the value @code{nil}, and no @var{else-forms} are
163 given, @code{if} returns @code{nil}.
165 @code{if} is a special form because the branch that is not selected is
166 never evaluated---it is ignored. Thus, in the example below,
167 @code{true} is not printed because @code{print} is never called.
179 @defspec cond clause@dots{}
180 @code{cond} chooses among an arbitrary number of alternatives. Each
181 @var{clause} in the @code{cond} must be a list. The @sc{car} of this
182 list is the @var{condition}; the remaining elements, if any, the
183 @var{body-forms}. Thus, a clause looks like this:
186 (@var{condition} @var{body-forms}@dots{})
189 @code{cond} tries the clauses in textual order, by evaluating the
190 @var{condition} of each clause. If the value of @var{condition} is
191 non-@code{nil}, the clause ``succeeds''; then @code{cond} evaluates its
192 @var{body-forms}, and the value of the last of @var{body-forms} becomes
193 the value of the @code{cond}. The remaining clauses are ignored.
195 If the value of @var{condition} is @code{nil}, the clause ``fails'', so
196 the @code{cond} moves on to the following clause, trying its
199 If every @var{condition} evaluates to @code{nil}, so that every clause
200 fails, @code{cond} returns @code{nil}.
202 A clause may also look like this:
209 Then, if @var{condition} is non-@code{nil} when tested, the value of
210 @var{condition} becomes the value of the @code{cond} form.
212 The following example has four clauses, which test for the cases where
213 the value of @code{x} is a number, string, buffer and symbol,
218 (cond ((numberp x) x)
221 (setq temporary-hack x) ; @r{multiple body-forms}
222 (buffer-name x)) ; @r{in one clause}
223 ((symbolp x) (symbol-value x)))
227 Often we want to execute the last clause whenever none of the previous
228 clauses was successful. To do this, we use @code{t} as the
229 @var{condition} of the last clause, like this: @code{(t
230 @var{body-forms})}. The form @code{t} evaluates to @code{t}, which is
231 never @code{nil}, so this clause never fails, provided the @code{cond}
238 (cond ((eq a 'hack) 'foo)
245 This expression is a @code{cond} which returns @code{foo} if the value
246 of @code{a} is 1, and returns the string @code{"default"} otherwise.
249 Any conditional construct can be expressed with @code{cond} or with
250 @code{if}. Therefore, the choice between them is a matter of style.
255 (if @var{a} @var{b} @var{c})
257 (cond (@var{a} @var{b}) (t @var{c}))
262 @node Combining Conditions
263 @section Constructs for Combining Conditions
265 This section describes three constructs that are often used together
266 with @code{if} and @code{cond} to express complicated conditions. The
267 constructs @code{and} and @code{or} can also be used individually as
268 kinds of multiple conditional constructs.
271 This function tests for the falsehood of @var{condition}. It returns
272 @code{t} if @var{condition} is @code{nil}, and @code{nil} otherwise.
273 The function @code{not} is identical to @code{null}, and we recommend
274 using the name @code{null} if you are testing for an empty list.
277 @defspec and conditions@dots{}
278 The @code{and} special form tests whether all the @var{conditions} are
279 true. It works by evaluating the @var{conditions} one by one in the
282 If any of the @var{conditions} evaluates to @code{nil}, then the result
283 of the @code{and} must be @code{nil} regardless of the remaining
284 @var{conditions}; so @code{and} returns right away, ignoring the
285 remaining @var{conditions}.
287 If all the @var{conditions} turn out non-@code{nil}, then the value of
288 the last of them becomes the value of the @code{and} form.
290 Here is an example. The first condition returns the integer 1, which is
291 not @code{nil}. Similarly, the second condition returns the integer 2,
292 which is not @code{nil}. The third condition is @code{nil}, so the
293 remaining condition is never evaluated.
297 (and (print 1) (print 2) nil (print 3))
304 Here is a more realistic example of using @code{and}:
308 (if (and (consp foo) (eq (car foo) 'x))
309 (message "foo is a list starting with x"))
314 Note that @code{(car foo)} is not executed if @code{(consp foo)} returns
315 @code{nil}, thus avoiding an error.
317 @code{and} can be expressed in terms of either @code{if} or @code{cond}.
322 (and @var{arg1} @var{arg2} @var{arg3})
324 (if @var{arg1} (if @var{arg2} @var{arg3}))
326 (cond (@var{arg1} (cond (@var{arg2} @var{arg3}))))
331 @defspec or conditions@dots{}
332 The @code{or} special form tests whether at least one of the
333 @var{conditions} is true. It works by evaluating all the
334 @var{conditions} one by one in the order written.
336 If any of the @var{conditions} evaluates to a non-@code{nil} value, then
337 the result of the @code{or} must be non-@code{nil}; so @code{or} returns
338 right away, ignoring the remaining @var{conditions}. The value it
339 returns is the non-@code{nil} value of the condition just evaluated.
341 If all the @var{conditions} turn out @code{nil}, then the @code{or}
342 expression returns @code{nil}.
344 For example, this expression tests whether @code{x} is either 0 or
348 (or (eq x nil) (eq x 0))
351 Like the @code{and} construct, @code{or} can be written in terms of
352 @code{cond}. For example:
356 (or @var{arg1} @var{arg2} @var{arg3})
364 You could almost write @code{or} in terms of @code{if}, but not quite:
368 (if @var{arg1} @var{arg1}
369 (if @var{arg2} @var{arg2}
375 This is not completely equivalent because it can evaluate @var{arg1} or
376 @var{arg2} twice. By contrast, @code{(or @var{arg1} @var{arg2}
377 @var{arg3})} never evaluates any argument more than once.
386 Iteration means executing part of a program repetitively. For
387 example, you might want to repeat some computation once for each element
388 of a list, or once for each integer from 0 to @var{n}. You can do this
389 in SXEmacs Lisp with the special form @code{while}:
391 @defspec while condition forms@dots{}
392 @code{while} first evaluates @var{condition}. If the result is
393 non-@code{nil}, it evaluates @var{forms} in textual order. Then it
394 reevaluates @var{condition}, and if the result is non-@code{nil}, it
395 evaluates @var{forms} again. This process repeats until @var{condition}
396 evaluates to @code{nil}.
398 There is no limit on the number of iterations that may occur. The loop
399 will continue until either @var{condition} evaluates to @code{nil} or
400 until an error or @code{throw} jumps out of it (@pxref{Nonlocal Exits}).
402 The value of a @code{while} form is always @code{nil}.
411 (princ (format "Iteration %d." num))
413 @print{} Iteration 0.
414 @print{} Iteration 1.
415 @print{} Iteration 2.
416 @print{} Iteration 3.
421 If you would like to execute something on each iteration before the
422 end-test, put it together with the end-test in a @code{progn} as the
423 first argument of @code{while}, as shown here:
429 (not (looking-at "^$"))))
434 This moves forward one line and continues moving by lines until it
435 reaches an empty. It is unusual in that the @code{while} has no body,
436 just the end test (which also does the real work of moving point).
439 Another---more powerful---way to do iteration is using the special
440 CL-macro @code{loop} but requires the @file{cl-macs} library to be
442 @c description here anyway?
446 @section Nonlocal Exits
447 @cindex nonlocal exits
449 A @dfn{nonlocal exit} is a transfer of control from one point in a
450 program to another remote point. Nonlocal exits can occur in SXEmacs
451 Lisp as a result of errors; you can also use them under explicit
452 control. Nonlocal exits unbind all variable bindings made by the
453 constructs being exited.
456 * Catch and Throw:: Nonlocal exits for the program's own purposes.
457 * Examples of Catch:: Showing how such nonlocal exits can be written.
458 * Errors:: How errors are signaled and handled.
459 * Cleanups:: Arranging to run a cleanup form if an error happens.
463 @node Catch and Throw
464 @subsection Explicit Nonlocal Exits: @code{catch} and @code{throw}
466 Most control constructs affect only the flow of control within the
467 construct itself. The function @code{throw} is the exception to this
468 rule of normal program execution: it performs a nonlocal exit on
469 request. (There are other exceptions, but they are for error handling
470 only.) @code{throw} is used inside a @code{catch}, and jumps back to
471 that @code{catch}. For example:
484 The @code{throw} transfers control straight back to the corresponding
485 @code{catch}, which returns immediately. The code following the
486 @code{throw} is not executed. The second argument of @code{throw} is used
487 as the return value of the @code{catch}.
489 The @code{throw} and the @code{catch} are matched through the first
490 argument: @code{throw} searches for a @code{catch} whose first argument
491 is @code{eq} to the one specified. Thus, in the above example, the
492 @code{throw} specifies @code{foo}, and the @code{catch} specifies the
493 same symbol, so that @code{catch} is applicable. If there is more than
494 one applicable @code{catch}, the innermost one takes precedence.
496 Executing @code{throw} exits all Lisp constructs up to the matching
497 @code{catch}, including function calls. When binding constructs such as
498 @code{let} or function calls are exited in this way, the bindings are
499 unbound, just as they are when these constructs exit normally
500 (@pxref{Local Variables}). Likewise, @code{throw} restores the buffer
501 and position saved by @code{save-excursion} (@pxref{Excursions}), and
502 the narrowing status saved by @code{save-restriction} and the window
503 selection saved by @code{save-window-excursion} (@pxref{Window
504 Configurations}). It also runs any cleanups established with the
505 @code{unwind-protect} special form when it exits that form
508 The @code{throw} need not appear lexically within the @code{catch}
509 that it jumps to. It can equally well be called from another function
510 called within the @code{catch}. As long as the @code{throw} takes place
511 chronologically after entry to the @code{catch}, and chronologically
512 before exit from it, it has access to that @code{catch}. This is why
513 @code{throw} can be used in commands such as @code{exit-recursive-edit}
514 that throw back to the editor command loop (@pxref{Recursive Editing}).
516 @cindex CL note---only @code{throw} in SXEmacs
518 @b{Common Lisp note:} Most other versions of Lisp, including Common Lisp,
519 have several ways of transferring control nonsequentially: @code{return},
520 @code{return-from}, and @code{go}, for example. SXEmacs Lisp has only
524 @defspec catch tag body@dots{}
525 @cindex tag on run time stack
526 @code{catch} establishes a return point for the @code{throw} function. The
527 return point is distinguished from other such return points by @var{tag},
528 which may be any Lisp object. The argument @var{tag} is evaluated normally
529 before the return point is established.
531 With the return point in effect, @code{catch} evaluates the forms of the
532 @var{body} in textual order. If the forms execute normally, without
533 error or nonlocal exit, the value of the last body form is returned from
536 If a @code{throw} is done within @var{body} specifying the same value
537 @var{tag}, the @code{catch} exits immediately; the value it returns is
538 whatever was specified as the second argument of @code{throw}.
541 @defun throw tag value
542 The purpose of @code{throw} is to return from a return point previously
543 established with @code{catch}. The argument @var{tag} is used to choose
544 among the various existing return points; it must be @code{eq} to the value
545 specified in the @code{catch}. If multiple return points match @var{tag},
546 the innermost one is used.
548 The argument @var{value} is used as the value to return from that
552 If no return point is in effect with tag @var{tag}, then a @code{no-catch}
553 error is signaled with data @code{(@var{tag} @var{value})}.
557 @node Examples of Catch
558 @subsection Examples of @code{catch} and @code{throw}
560 One way to use @code{catch} and @code{throw} is to exit from a doubly
561 nested loop. (In most languages, this would be done with a ``go to''.)
562 Here we compute @code{(foo @var{i} @var{j})} for @var{i} and @var{j}
574 (throw 'loop (list i j)))
581 If @code{foo} ever returns non-@code{nil}, we stop immediately and return a
582 list of @var{i} and @var{j}. If @code{foo} always returns @code{nil}, the
583 @code{catch} returns normally, and the value is @code{nil}, since that
584 is the result of the @code{while}.
586 Here are two tricky examples, slightly different, showing two
587 return points at once. First, two return points with the same tag,
600 (print (catch2 'hack))
608 Since both return points have tags that match the @code{throw}, it goes to
609 the inner one, the one established in @code{catch2}. Therefore,
610 @code{catch2} returns normally with value @code{yes}, and this value is
611 printed. Finally the second body form in the outer @code{catch}, which is
612 @code{'no}, is evaluated and returned from the outer @code{catch}.
614 Now let's change the argument given to @code{catch2}:
626 (print (catch2 'quux))
633 We still have two return points, but this time only the outer one has
634 the tag @code{hack}; the inner one has the tag @code{quux} instead.
635 Therefore, @code{throw} makes the outer @code{catch} return the value
636 @code{yes}. The function @code{print} is never called, and the
637 body-form @code{'no} is never evaluated.
644 When SXEmacs Lisp attempts to evaluate a form that, for some reason,
645 cannot be evaluated, it @dfn{signals} an @dfn{error}.
647 When an error is signaled, SXEmacs's default reaction is to print an
648 error message and terminate execution of the current command. This is
649 the right thing to do in most cases, such as if you type @kbd{C-f} at
650 the end of the buffer.
652 In complicated programs, simple termination may not be what you want.
653 For example, the program may have made temporary changes in data
654 structures, or created temporary buffers that should be deleted before
655 the program is finished. In such cases, you would use
656 @code{unwind-protect} to establish @dfn{cleanup expressions} to be
657 evaluated in case of error. (@xref{Cleanups}.)
659 Occasionally, you may wish the program to continue execution despite an
660 error in a subroutine. In these cases, you would use
661 @code{condition-case} to establish @dfn{error handlers} to recover
662 control in case of error.
664 Resist the temptation to use error handling to transfer control from
665 one part of the program to another; use @code{catch} and @code{throw}
666 instead. @xref{Catch and Throw}.
669 * Signaling Errors:: How to report an error.
670 * Processing of Errors:: What SXEmacs does when you report an error.
671 * Handling Errors:: How you can trap errors and continue execution.
672 * Error Symbols:: How errors are classified for trapping them.
676 @node Signaling Errors
677 @subsubsection How to Signal an Error
678 @cindex signaling errors
680 Most errors are signaled ``automatically'' within Lisp primitives
681 which you call for other purposes, such as if you try to take the
682 @sc{car} of an integer or move forward a character at the end of the
683 buffer; you can also signal errors explicitly with the functions
684 @code{error}, @code{signal}, and others.
686 Quitting, which happens when the user types @kbd{C-g}, is not
687 considered an error, but it is handled almost like an error.
690 SXEmacs has a rich hierarchy of error symbols predefined via
699 malformed-property-list
701 circular-property-list
706 wrong-number-of-arguments
712 cyclic-function-indirection
714 cyclic-variable-indirection
733 The five most common errors you will probably use or base your new
734 errors off of are @code{syntax-error}, @code{invalid-argument},
735 @code{invalid-state}, @code{invalid-operation}, and
736 @code{invalid-change}. Note the semantic differences:
740 @code{syntax-error} is for errors in complex structures: parsed strings,
744 @code{invalid-argument} is for errors in a simple value. Typically, the
745 entire value, not just one part of it, is wrong.
748 @code{invalid-state} means that some settings have been changed in such
749 a way that their current state is unallowable. More and more, code is
750 being written more carefully, and catches the error when the settings
751 are being changed, rather than afterwards. This leads us to the next
755 @code{invalid-change} means that an attempt is being made to change some
756 settings into an invalid state. @code{invalid-change} is a type of
757 @code{invalid-operation}.
760 @code{invalid-operation} refers to all cases where code is trying to do
761 something that's disallowed. This includes file errors, buffer errors
762 (e.g. running off the end of a buffer), @code{invalid-change} as just
763 mentioned, and arithmetic errors.
766 @defun error datum &rest args
767 This function signals a non-continuable error.
769 @var{datum} should normally be an error symbol, i.e. a symbol defined
770 using @code{define-error}. @var{args} will be made into a list, and
771 @var{datum} and @var{args} passed as the two arguments to @code{signal},
772 the most basic error handling function.
774 This error is not continuable: you cannot continue execution after the
775 error using the debugger @kbd{r} command. See also @code{cerror}.
777 The correct semantics of @var{args} varies from error to error, but for
778 most errors that need to be generated in Lisp code, the first argument
779 should be a string describing the *context* of the error (i.e. the exact
780 operation being performed and what went wrong), and the remaining
781 arguments or \"frobs\" (most often, there is one) specify the offending
782 object(s) and/or provide additional details such as the exact error when
783 a file error occurred, e.g.:
787 the buffer in which an editing error occurred.
789 an invalid value that was encountered. (In such cases, the string
790 should describe the purpose or \"semantics\" of the value [e.g. if the
791 value is an argument to a function, the name of the argument; if the value
792 is the value corresponding to a keyword, the name of the keyword; if the
793 value is supposed to be a list length, say this and say what the purpose
794 of the list is; etc.] as well as specifying why the value is invalid, if
795 that's not self-evident.)
797 the file in which an error occurred. (In such cases, there should be a
798 second frob, probably a string, specifying the exact error that occurred.
799 This does not occur in the string that precedes the first frob, because
800 that frob describes the exact operation that was happening.
803 For historical compatibility, DATUM can also be a string. In this case,
804 @var{datum} and @var{args} are passed together as the arguments to
805 @code{format}, and then an error is signalled using the error symbol
806 @code{error} and formatted string. Although this usage of @code{error}
807 is very common, it is deprecated because it totally defeats the purpose
808 of having structured errors. There is now a rich set of defined errors
811 See also @code{cerror}, @code{signal}, and @code{signal-error}."
813 These examples show typical uses of @code{error}:
818 "Dialog descriptor must supply at least one button"
823 (error "You have committed an error.
824 Try something else.")
825 @error{} You have committed an error.
830 (error "You have committed %d errors." 10)
831 @error{} You have committed 10 errors.
835 If you want to use your own string as an error message verbatim, don't
836 just write @code{(error @var{string})}. If @var{string} contains
837 @samp{%}, it will be interpreted as a format specifier, with undesirable
838 results. Instead, use @code{(error "%s" @var{string})}.
841 @defun cerror datum &rest args
842 This function behaves like @code{error}, except that the error it
843 signals is continuable. That means that debugger commands @kbd{c} and
844 @kbd{r} can resume execution.
847 @defun signal error-symbol data
848 This function signals a continuable error named by @var{error-symbol}.
849 The argument @var{data} is a list of additional Lisp objects relevant to
850 the circumstances of the error.
852 The argument @var{error-symbol} must be an @dfn{error symbol}---a symbol
853 bearing a property @code{error-conditions} whose value is a list of
854 condition names. This is how SXEmacs Lisp classifies different sorts of
857 The number and significance of the objects in @var{data} depends on
858 @var{error-symbol}. For example, with a @code{wrong-type-argument}
859 error, there are two objects in the list: a predicate that describes the
860 type that was expected, and the object that failed to fit that type.
861 @xref{Error Symbols}, for a description of error symbols.
863 Both @var{error-symbol} and @var{data} are available to any error
864 handlers that handle the error: @code{condition-case} binds a local
865 variable to a list of the form @code{(@var{error-symbol} .@:
866 @var{data})} (@pxref{Handling Errors}). If the error is not handled,
867 these two values are used in printing the error message.
869 The function @code{signal} can return, if the debugger is invoked and
870 the user invokes the ``return from signal'' option. If you want the
871 error not to be continuable, use @code{signal-error} instead.
873 Note: In FSF Emacs @code{signal} never returns.
877 (signal 'wrong-number-of-arguments '(x y))
878 @error{} Wrong number of arguments: x, y
882 (signal 'no-such-error '("My unknown error condition"))
883 @error{} Peculiar error (no-such-error "My unknown error condition")
888 @defun signal-error error-symbol data
889 This function behaves like @code{signal}, except that the error it
890 signals is not continuable.
893 @defmac check-argument-type predicate argument
894 This macro checks that @var{argument} satisfies @var{predicate}. If
895 that is not the case, it signals a continuable
896 @code{wrong-type-argument} error until the returned value satisfies
897 @var{predicate}, and assigns the returned value to @var{argument}. In
898 other words, execution of the program will not continue until
899 @var{predicate} is met.
901 @var{argument} is not evaluated, and should be a symbol.
902 @var{predicate} is evaluated, and should name a function.
904 As shown in the following example, @code{check-argument-type} is useful
905 in low-level code that attempts to ensure the sanity of its data before
910 (defun cache-object-internal (object wlist)
911 ;; @r{Before doing anything, make sure that @var{wlist} is indeed}
912 ;; @r{a weak list, which is what we expect.}
913 (check-argument-type 'weak-list-p wlist)
920 @node Processing of Errors
921 @subsubsection How SXEmacs Processes Errors
923 When an error is signaled, @code{signal} searches for an active
924 @dfn{handler} for the error. A handler is a sequence of Lisp
925 expressions designated to be executed if an error happens in part of the
926 Lisp program. If the error has an applicable handler, the handler is
927 executed, and control resumes following the handler.
929 The handler executes in the environment of the @code{condition-case}
930 that established it; all functions called within that
931 @code{condition-case} have already been exited, and the handler cannot
934 If there is no applicable handler for the error, the current command is
935 terminated and control returns to the editor command loop, because the
936 command loop has an implicit handler for all kinds of errors. The
937 command loop's handler uses the error symbol and associated data to
938 print an error message.
940 Errors in command loop are processed using the @code{command-error}
941 function, which takes care of some necessary cleanup, and prints a
942 formatted error message to the echo area. The functions that do the
943 formatting are explained below.
945 @defun display-error error-object stream
946 This function displays @var{error-object} on @var{stream}.
947 @var{error-object} is a cons of error type, a symbol, and error
948 arguments, a list. If the error type symbol of one of its error
949 condition superclasses has a @code{display-error} property, that
950 function is invoked for printing the actual error message. Otherwise,
951 the error is printed as @samp{Error: arg1, arg2, ...}.
954 @defun error-message-string error-object
955 This function converts @var{error-object} to an error message string,
956 and returns it. The message is equivalent to the one that would be
957 printed by @code{display-error}, except that it is conveniently returned
961 @cindex @code{debug-on-error} use
962 An error that has no explicit handler may call the Lisp debugger. The
963 debugger is enabled if the variable @code{debug-on-error} (@pxref{Error
964 Debugging}) is non-@code{nil}. Unlike error handlers, the debugger runs
965 in the environment of the error, so that you can examine values of
966 variables precisely as they were at the time of the error.
969 @node Handling Errors
970 @subsubsection Writing Code to Handle Errors
971 @cindex error handler
972 @cindex handling errors
974 The usual effect of signaling an error is to terminate the command
975 that is running and return immediately to the SXEmacs editor command
976 loop. You can arrange to trap errors occurring in a part of your program
977 by establishing an error handler, with the special form
978 @code{condition-case}. A simple example looks like this:
983 (delete-file filename)
989 This deletes the file named @var{filename}, catching any error and
990 returning @code{nil} if an error occurs.
992 The second argument of @code{condition-case} is called the
993 @dfn{protected form}. (In the example above, the protected form is a
994 call to @code{delete-file}.) The error handlers go into effect when
995 this form begins execution and are deactivated when this form returns.
996 They remain in effect for all the intervening time.
998 In particular, they are in effect during the execution of functions
999 called by this form, in their subroutines, and so on. This is a good
1000 thing, since, strictly speaking, errors can be signaled only by Lisp
1001 primitives (including @code{signal} and @code{error}) called by the
1002 protected form, not by the protected form itself.
1004 The arguments after the protected form are handlers. Each handler
1005 lists one or more @dfn{condition names} (which are symbols) to specify
1006 which errors it will handle. The error symbol specified when an error
1007 is signaled also defines a list of condition names. A handler applies
1008 to an error if they have any condition names in common. In the example
1009 above, there is one handler, and it specifies one condition name,
1010 @code{error}, which covers all errors.
1012 The search for an applicable handler checks all the established handlers
1013 starting with the most recently established one. Thus, if two nested
1014 @code{condition-case} forms offer to handle the same error, the inner of
1015 the two will actually handle it.
1017 When an error is handled, control returns to the handler. Before this
1018 happens, SXEmacs unbinds all variable bindings made by binding
1019 constructs that are being exited and executes the cleanups of all
1020 @code{unwind-protect} forms that are exited. Once control arrives at
1021 the handler, the body of the handler is executed.
1023 After execution of the handler body, execution continues by returning
1024 from the @code{condition-case} form. Because the protected form is
1025 exited completely before execution of the handler, the handler cannot
1026 resume execution at the point of the error, nor can it examine variable
1027 bindings that were made within the protected form. All it can do is
1028 clean up and proceed.
1030 @code{condition-case} is often used to trap errors that are
1031 predictable, such as failure to open a file in a call to
1032 @code{insert-file-contents}. It is also used to trap errors that are
1033 totally unpredictable, such as when the program evaluates an expression
1036 @cindex @code{debug-on-signal} use
1037 Even when an error is handled, the debugger may still be called if the
1038 variable @code{debug-on-signal} (@pxref{Error Debugging}) is
1039 non-@code{nil}. Note that this may yield unpredictable results with
1040 code that traps expected errors as normal part of its operation. Do not
1041 set @code{debug-on-signal} unless you know what you are doing.
1043 Error signaling and handling have some resemblance to @code{throw} and
1044 @code{catch}, but they are entirely separate facilities. An error
1045 cannot be caught by a @code{catch}, and a @code{throw} cannot be handled
1046 by an error handler (though using @code{throw} when there is no suitable
1047 @code{catch} signals an error that can be handled).
1049 @defspec condition-case var protected-form handlers@dots{}
1050 This special form establishes the error handlers @var{handlers} around
1051 the execution of @var{protected-form}. If @var{protected-form} executes
1052 without error, the value it returns becomes the value of the
1053 @code{condition-case} form; in this case, the @code{condition-case} has
1054 no effect. The @code{condition-case} form makes a difference when an
1055 error occurs during @var{protected-form}.
1057 Each of the @var{handlers} is a list of the form @code{(@var{conditions}
1058 @var{body}@dots{})}. Here @var{conditions} is an error condition name
1059 to be handled, or a list of condition names; @var{body} is one or more
1060 Lisp expressions to be executed when this handler handles an error.
1061 Here are examples of handlers:
1067 (arith-error (message "Division by zero"))
1069 ((arith-error file-error)
1071 "Either division by zero or failure to open a file"))
1075 Each error that occurs has an @dfn{error symbol} that describes what
1076 kind of error it is. The @code{error-conditions} property of this
1077 symbol is a list of condition names (@pxref{Error Symbols}). SXEmacs
1078 searches all the active @code{condition-case} forms for a handler that
1079 specifies one or more of these condition names; the innermost matching
1080 @code{condition-case} handles the error. Within this
1081 @code{condition-case}, the first applicable handler handles the error.
1083 After executing the body of the handler, the @code{condition-case}
1084 returns normally, using the value of the last form in the handler body
1085 as the overall value.
1087 The argument @var{var} is a variable. @code{condition-case} does not
1088 bind this variable when executing the @var{protected-form}, only when it
1089 handles an error. At that time, it binds @var{var} locally to a list of
1090 the form @code{(@var{error-symbol} . @var{data})}, giving the
1091 particulars of the error. The handler can refer to this list to decide
1092 what to do. For example, if the error is for failure opening a file,
1093 the file name is the second element of @var{data}---the third element of
1096 If @var{var} is @code{nil}, that means no variable is bound. Then the
1097 error symbol and associated data are not available to the handler.
1100 @cindex @code{arith-error} example
1101 Here is an example of using @code{condition-case} to handle the error
1102 that results from dividing by zero. The handler prints out a warning
1103 message and returns a very large number.
1107 (defun safe-divide (dividend divisor)
1109 ;; @r{Protected form.}
1110 (/ dividend divisor)
1112 (arith-error ; @r{Condition.}
1113 (princ (format "Arithmetic error: %s" err))
1115 @result{} safe-divide
1120 @print{} Arithmetic error: (arith-error)
1126 The handler specifies condition name @code{arith-error} so that it will
1127 handle only division-by-zero errors. Other kinds of errors will not be
1128 handled, at least not by this @code{condition-case}. Thus,
1133 @error{} Wrong type argument: integer-or-marker-p, nil
1137 Here is a @code{condition-case} that catches all kinds of errors,
1138 including those signaled with @code{error}:
1150 ;; @r{This is a call to the function @code{error}.}
1151 (error "Rats! The variable %s was %s, not 35" 'baz baz))
1152 ;; @r{This is the handler; it is not a form.}
1153 (error (princ (format "The error was: %s" err))
1155 @print{} The error was: (error "Rats! The variable baz was 34, not 35")
1162 @subsubsection Error Symbols and Condition Names
1163 @cindex error symbol
1165 @cindex condition name
1166 @cindex user-defined error
1167 @kindex error-conditions
1169 When you signal an error, you specify an @dfn{error symbol} to specify
1170 the kind of error you have in mind. Each error has one and only one
1171 error symbol to categorize it. This is the finest classification of
1172 errors defined by the SXEmacs Lisp language.
1174 These narrow classifications are grouped into a hierarchy of wider
1175 classes called @dfn{error conditions}, identified by @dfn{condition
1176 names}. The narrowest such classes belong to the error symbols
1177 themselves: each error symbol is also a condition name. There are also
1178 condition names for more extensive classes, up to the condition name
1179 @code{error} which takes in all kinds of errors. Thus, each error has
1180 one or more condition names: @code{error}, the error symbol if that
1181 is distinct from @code{error}, and perhaps some intermediate
1184 In other words, each error condition @dfn{inherits} from another error
1185 condition, with @code{error} sitting at the top of the inheritance
1188 @defun define-error error-symbol error-message &optional inherits-from
1189 This function defines a new error, denoted by @var{error-symbol}.
1190 @var{error-message} is an informative message explaining the error, and
1191 will be printed out when an unhandled error occurs. @var{error-symbol}
1192 is a sub-error of @var{inherits-from} (which defaults to @code{error}).
1194 @code{define-error} internally works by putting on @var{error-symbol}
1195 an @code{error-message} property whose value is @var{error-message}, and
1196 an @code{error-conditions} property that is a list of @var{error-symbol}
1197 followed by each of its super-errors, up to and including @code{error}.
1199 Note: You will sometimes see code that sets this up directly rather than
1200 calling @code{define-error}, but you should @emph{not} do this yourself,
1201 unless you wish to maintain compatibility with FSF Emacs, which does not
1202 provide @code{define-error}.
1205 Here is how we define a new error symbol, @code{new-error}, that
1206 belongs to a range of errors called @code{my-own-errors}:
1210 (define-error 'my-own-errors "A whole range of errors" 'error)
1211 (define-error 'new-error "A new error" 'my-own-errors)
1216 @code{new-error} has three condition names: @code{new-error}, the
1217 narrowest classification; @code{my-own-errors}, which we imagine is a
1218 wider classification; and @code{error}, which is the widest of all.
1220 Note: It is not legal to try to define an error unless its
1221 super-error is also defined. For instance, attempting to define
1222 @code{new-error} before @code{my-own-errors} are defined will signal an
1225 The error string should start with a capital letter but it should
1226 not end with a period. This is for consistency with the rest of SXEmacs.
1228 Naturally, SXEmacs will never signal @code{new-error} on its own; only
1229 an explicit call to @code{signal} (@pxref{Signaling Errors}) in your
1234 (signal 'new-error '(x y))
1235 @error{} A new error: x, y
1239 This error can be handled through any of the three condition names.
1240 This example handles @code{new-error} and any other errors in the class
1241 @code{my-own-errors}:
1247 (my-own-errors nil))
1251 The significant way that errors are classified is by their condition
1252 names---the names used to match errors with handlers. An error symbol
1253 serves only as a convenient way to specify the intended error message
1254 and list of condition names. It would be cumbersome to give
1255 @code{signal} a list of condition names rather than one error symbol.
1257 By contrast, using only error symbols without condition names would
1258 seriously decrease the power of @code{condition-case}. Condition names
1259 make it possible to categorize errors at various levels of generality
1260 when you write an error handler. Using error symbols alone would
1261 eliminate all but the narrowest level of classification.
1263 @xref{Standard Errors}, for a list of all the standard error symbols
1264 and their conditions.
1268 @subsection Cleaning Up from Nonlocal Exits
1270 The @code{unwind-protect} construct is essential whenever you
1271 temporarily put a data structure in an inconsistent state; it permits
1272 you to ensure the data are consistent in the event of an error or throw.
1274 @defspec unwind-protect body cleanup-forms@dots{}
1275 @cindex cleanup forms
1276 @cindex protected forms
1277 @cindex error cleanup
1279 @code{unwind-protect} executes the @var{body} with a guarantee that the
1280 @var{cleanup-forms} will be evaluated if control leaves @var{body}, no
1281 matter how that happens. The @var{body} may complete normally, or
1282 execute a @code{throw} out of the @code{unwind-protect}, or cause an
1283 error; in all cases, the @var{cleanup-forms} will be evaluated.
1285 If the @var{body} forms finish normally, @code{unwind-protect} returns
1286 the value of the last @var{body} form, after it evaluates the
1287 @var{cleanup-forms}. If the @var{body} forms do not finish,
1288 @code{unwind-protect} does not return any value in the normal sense.
1290 Only the @var{body} is actually protected by the @code{unwind-protect}.
1291 If any of the @var{cleanup-forms} themselves exits nonlocally (e.g., via
1292 a @code{throw} or an error), @code{unwind-protect} is @emph{not}
1293 guaranteed to evaluate the rest of them. If the failure of one of the
1294 @var{cleanup-forms} has the potential to cause trouble, then protect it
1295 with another @code{unwind-protect} around that form.
1297 The number of currently active @code{unwind-protect} forms counts,
1298 together with the number of local variable bindings, against the limit
1299 @code{max-specpdl-size} (@pxref{Local Variables}).
1302 For example, here we make an invisible buffer for temporary use, and
1303 make sure to kill it before finishing:
1308 (let ((buffer (get-buffer-create " *temp*")))
1312 (kill-buffer buffer))))
1317 You might think that we could just as well write @code{(kill-buffer
1318 (current-buffer))} and dispense with the variable @code{buffer}.
1319 However, the way shown above is safer, if @var{body} happens to get an
1320 error after switching to a different buffer! Alternatively, you could
1321 write another @code{save-excursion} around the body, to ensure that the
1322 temporary buffer becomes current in time to kill it.
1325 Here is an actual example taken from the file @file{ftp.el}. It
1326 creates a process (@pxref{Processes}) to try to establish a connection
1327 to a remote machine. As the function @code{ftp-login} is highly
1328 susceptible to numerous problems that the writer of the function cannot
1329 anticipate, it is protected with a form that guarantees deletion of the
1330 process in the event of failure. Otherwise, SXEmacs might fill up with
1331 useless subprocesses.
1338 (setq process (ftp-setup-buffer host file))
1339 (if (setq win (ftp-login process host user password))
1340 (message "Logged in")
1341 (error "Ftp login failed")))
1342 (or win (and process (delete-process process)))))
1346 This example actually has a small bug: if the user types @kbd{C-g} to
1347 quit, and the quit happens immediately after the function
1348 @code{ftp-setup-buffer} returns but before the variable @code{process} is
1349 set, the process will not be killed. There is no easy way to fix this bug,
1350 but at least it is very unlikely.
1352 Here is another example which uses @code{unwind-protect} to make sure
1353 to kill a temporary buffer. In this example, the value returned by
1354 @code{unwind-protect} is used.
1357 (defun shell-command-string (cmd)
1358 "Return the output of the shell command CMD, as a string."
1360 (set-buffer (generate-new-buffer " OS*cmd"))
1361 (shell-command cmd t)
1364 (kill-buffer (current-buffer)))))