new version
[emacs.git] / lispref / control.texi
blob4d01661a9a1e950e5d7ce58266ae8129f8aa3aee
1 @c -*-texinfo-*-
2 @c This is part of the GNU Emacs Lisp Reference Manual.
3 @c Copyright (C) 1990, 1991, 1992, 1993, 1994 Free Software Foundation, Inc. 
4 @c See the file elisp.texi for copying conditions.
5 @setfilename ../info/control
6 @node Control Structures, Variables, Evaluation, Top
7 @chapter Control Structures
8 @cindex special forms for control structures
9 @cindex control structures
11   A Lisp program consists of expressions or @dfn{forms} (@pxref{Forms}).
12 We control the order of execution of the forms by enclosing them in
13 @dfn{control structures}.  Control structures are special forms which
14 control when, whether, or how many times to execute the forms they
15 contain.
17   The simplest order of execution is sequential execution: first form
18 @var{a}, then form @var{b}, and so on.  This is what happens when you
19 write several forms in succession in the body of a function, or at top
20 level in a file of Lisp code---the forms are executed in the order
21 written.  We call this @dfn{textual order}.  For example, if a function
22 body consists of two forms @var{a} and @var{b}, evaluation of the
23 function evaluates first @var{a} and then @var{b}, and the function's
24 value is the value of @var{b}.
26   Explicit control structures make possible an order of execution other
27 than sequential.
29   Emacs Lisp provides several kinds of control structure, including
30 other varieties of sequencing, conditionals, iteration, and (controlled)
31 jumps---all discussed below.  The built-in control structures are
32 special forms since their subforms are not necessarily evaluated or not
33 evaluated sequentially.  You can use macros to define your own control
34 structure constructs (@pxref{Macros}).
36 @menu
37 * Sequencing::             Evaluation in textual order.
38 * Conditionals::           @code{if}, @code{cond}.
39 * Combining Conditions::   @code{and}, @code{or}, @code{not}.
40 * Iteration::              @code{while} loops.
41 * Nonlocal Exits::         Jumping out of a sequence.
42 @end menu
44 @node Sequencing
45 @section Sequencing
47   Evaluating forms in the order they appear is the most common way
48 control passes from one form to another.  In some contexts, such as in a
49 function body, this happens automatically.  Elsewhere you must use a
50 control structure construct to do this: @code{progn}, the simplest
51 control construct of Lisp.
53   A @code{progn} special form looks like this:
55 @example
56 @group
57 (progn @var{a} @var{b} @var{c} @dots{})
58 @end group
59 @end example
61 @noindent
62 and it says to execute the forms @var{a}, @var{b}, @var{c} and so on, in
63 that order.  These forms are called the body of the @code{progn} form.
64 The value of the last form in the body becomes the value of the entire
65 @code{progn}.
67 @cindex implicit @code{progn}
68   In the early days of Lisp, @code{progn} was the only way to execute
69 two or more forms in succession and use the value of the last of them.
70 But programmers found they often needed to use a @code{progn} in the
71 body of a function, where (at that time) only one form was allowed.  So
72 the body of a function was made into an ``implicit @code{progn}'':
73 several forms are allowed just as in the body of an actual @code{progn}.
74 Many other control structures likewise contain an implicit @code{progn}.
75 As a result, @code{progn} is not used as often as it used to be.  It is
76 needed now most often inside an @code{unwind-protect}, @code{and},
77 @code{or}, or in the @var{then}-part of an @code{if}.
79 @defspec progn forms@dots{}
80 This special form evaluates all of the @var{forms}, in textual
81 order, returning the result of the final form.
83 @example
84 @group
85 (progn (print "The first form")
86        (print "The second form")
87        (print "The third form"))
88      @print{} "The first form"
89      @print{} "The second form"
90      @print{} "The third form"
91 @result{} "The third form"
92 @end group
93 @end example
94 @end defspec
96   Two other control constructs likewise evaluate a series of forms but return
97 a different value:
99 @defspec prog1 form1 forms@dots{}
100 This special form evaluates @var{form1} and all of the @var{forms}, in
101 textual order, returning the result of @var{form1}.
103 @example
104 @group
105 (prog1 (print "The first form")
106        (print "The second form")
107        (print "The third form"))
108      @print{} "The first form"
109      @print{} "The second form"
110      @print{} "The third form"
111 @result{} "The first form"
112 @end group
113 @end example
115 Here is a way to remove the first element from a list in the variable
116 @code{x}, then return the value of that former element:
118 @example
119 (prog1 (car x) (setq x (cdr x)))
120 @end example
121 @end defspec
123 @defspec prog2 form1 form2 forms@dots{}
124 This special form evaluates @var{form1}, @var{form2}, and all of the
125 following @var{forms}, in textual order, returning the result of
126 @var{form2}.
128 @example
129 @group
130 (prog2 (print "The first form")
131        (print "The second form")
132        (print "The third form"))
133      @print{} "The first form"
134      @print{} "The second form"
135      @print{} "The third form"
136 @result{} "The second form"
137 @end group
138 @end example
139 @end defspec
141 @node Conditionals
142 @section Conditionals
143 @cindex conditional evaluation
145   Conditional control structures choose among alternatives.  Emacs Lisp
146 has four conditional forms: @code{if}, which is much the same as in
147 other languages; @code{when} and @code{unless}, which are variants of
148 @code{if}; and @code{cond}, which is a generalized case statement.
150 @defspec if condition then-form else-forms@dots{}
151 @code{if} chooses between the @var{then-form} and the @var{else-forms}
152 based on the value of @var{condition}.  If the evaluated @var{condition} is
153 non-@code{nil}, @var{then-form} is evaluated and the result returned.
154 Otherwise, the @var{else-forms} are evaluated in textual order, and the
155 value of the last one is returned.  (The @var{else} part of @code{if} is
156 an example of an implicit @code{progn}.  @xref{Sequencing}.) 
158 If @var{condition} has the value @code{nil}, and no @var{else-forms} are
159 given, @code{if} returns @code{nil}.
161 @code{if} is a special form because the branch that is not selected is
162 never evaluated---it is ignored.  Thus, in the example below,
163 @code{true} is not printed because @code{print} is never called.
165 @example
166 @group
167 (if nil 
168     (print 'true) 
169   'very-false)
170 @result{} very-false
171 @end group
172 @end example
173 @end defspec
175 @defspec when condition then-forms@dots{}
176 This is a variant of @code{if} where there are no @var{else-forms},
177 and possibly several @var{then-forms}.  In particular,
179 @example
180 (when @var{condition} @var{a} @var{b} @var{c})
181 @end example
183 @noindent
184 is entirely equivalent to
186 @example
187 (if @var{condition} (progn @var{a} @var{b} @var{c}) nil)
188 @end example
189 @end defspec
191 @defspec unless condition forms@dots{}
192 This is a variant of @code{if} where there is no @var{then-form}:
194 @example
195 (unless @var{condition} @var{a} @var{b} @var{c})
196 @end example
198 @noindent
199 is entirely equivalent to
201 @example
202 (if @var{condition} nil
203    @var{a} @var{b} @var{c})
204 @end example
205 @end defspec
207 @defspec cond clause@dots{}
208 @code{cond} chooses among an arbitrary number of alternatives.  Each
209 @var{clause} in the @code{cond} must be a list.  The @sc{car} of this
210 list is the @var{condition}; the remaining elements, if any, the
211 @var{body-forms}.  Thus, a clause looks like this:
213 @example
214 (@var{condition} @var{body-forms}@dots{})
215 @end example
217 @code{cond} tries the clauses in textual order, by evaluating the
218 @var{condition} of each clause.  If the value of @var{condition} is
219 non-@code{nil}, the clause ``succeeds''; then @code{cond} evaluates its
220 @var{body-forms}, and the value of the last of @var{body-forms} becomes
221 the value of the @code{cond}.  The remaining clauses are ignored.
223 If the value of @var{condition} is @code{nil}, the clause ``fails'', so
224 the @code{cond} moves on to the following clause, trying its
225 @var{condition}.
227 If every @var{condition} evaluates to @code{nil}, so that every clause
228 fails, @code{cond} returns @code{nil}.
230 A clause may also look like this:
232 @example
233 (@var{condition})
234 @end example
236 @noindent
237 Then, if @var{condition} is non-@code{nil} when tested, the value of
238 @var{condition} becomes the value of the @code{cond} form.
240 The following example has four clauses, which test for the cases where
241 the value of @code{x} is a number, string, buffer and symbol,
242 respectively:
244 @example
245 @group
246 (cond ((numberp x) x)
247       ((stringp x) x)
248       ((bufferp x)
249        (setq temporary-hack x) ; @r{multiple body-forms}
250        (buffer-name x))        ; @r{in one clause}
251       ((symbolp x) (symbol-value x)))
252 @end group
253 @end example
255 Often we want to execute the last clause whenever none of the previous
256 clauses was successful.  To do this, we use @code{t} as the
257 @var{condition} of the last clause, like this: @code{(t
258 @var{body-forms})}.  The form @code{t} evaluates to @code{t}, which is
259 never @code{nil}, so this clause never fails, provided the @code{cond}
260 gets to it at all.
262 For example, 
264 @example
265 @group
266 (cond ((eq a 'hack) 'foo)
267       (t "default"))
268 @result{} "default"
269 @end group
270 @end example
272 @noindent
273 This expression is a @code{cond} which returns @code{foo} if the value
274 of @code{a} is 1, and returns the string @code{"default"} otherwise.
275 @end defspec
277 Any conditional construct can be expressed with @code{cond} or with
278 @code{if}.  Therefore, the choice between them is a matter of style.
279 For example:
281 @example
282 @group
283 (if @var{a} @var{b} @var{c})
284 @equiv{}
285 (cond (@var{a} @var{b}) (t @var{c}))
286 @end group
287 @end example
289 @node Combining Conditions
290 @section Constructs for Combining Conditions
292   This section describes three constructs that are often used together
293 with @code{if} and @code{cond} to express complicated conditions.  The
294 constructs @code{and} and @code{or} can also be used individually as
295 kinds of multiple conditional constructs.
297 @defun not condition
298 This function tests for the falsehood of @var{condition}.  It returns
299 @code{t} if @var{condition} is @code{nil}, and @code{nil} otherwise.
300 The function @code{not} is identical to @code{null}, and we recommend
301 using the name @code{null} if you are testing for an empty list.
302 @end defun
304 @defspec and conditions@dots{}
305 The @code{and} special form tests whether all the @var{conditions} are
306 true.  It works by evaluating the @var{conditions} one by one in the
307 order written.
309 If any of the @var{conditions} evaluates to @code{nil}, then the result
310 of the @code{and} must be @code{nil} regardless of the remaining
311 @var{conditions}; so @code{and} returns right away, ignoring the
312 remaining @var{conditions}.
314 If all the @var{conditions} turn out non-@code{nil}, then the value of
315 the last of them becomes the value of the @code{and} form.
317 Here is an example.  The first condition returns the integer 1, which is
318 not @code{nil}.  Similarly, the second condition returns the integer 2,
319 which is not @code{nil}.  The third condition is @code{nil}, so the
320 remaining condition is never evaluated.
322 @example
323 @group
324 (and (print 1) (print 2) nil (print 3))
325      @print{} 1
326      @print{} 2
327 @result{} nil
328 @end group
329 @end example
331 Here is a more realistic example of using @code{and}:
333 @example
334 @group
335 (if (and (consp foo) (eq (car foo) 'x))
336     (message "foo is a list starting with x"))
337 @end group
338 @end example
340 @noindent
341 Note that @code{(car foo)} is not executed if @code{(consp foo)} returns
342 @code{nil}, thus avoiding an error.
344 @code{and} can be expressed in terms of either @code{if} or @code{cond}.
345 For example:
347 @example
348 @group
349 (and @var{arg1} @var{arg2} @var{arg3})
350 @equiv{}
351 (if @var{arg1} (if @var{arg2} @var{arg3}))
352 @equiv{}
353 (cond (@var{arg1} (cond (@var{arg2} @var{arg3}))))
354 @end group
355 @end example
356 @end defspec
358 @defspec or conditions@dots{}
359 The @code{or} special form tests whether at least one of the
360 @var{conditions} is true.  It works by evaluating all the
361 @var{conditions} one by one in the order written.
363 If any of the @var{conditions} evaluates to a non-@code{nil} value, then
364 the result of the @code{or} must be non-@code{nil}; so @code{or} returns
365 right away, ignoring the remaining @var{conditions}.  The value it
366 returns is the non-@code{nil} value of the condition just evaluated.
368 If all the @var{conditions} turn out @code{nil}, then the @code{or}
369 expression returns @code{nil}.
371 For example, this expression tests whether @code{x} is either 0 or
372 @code{nil}:
374 @example
375 (or (eq x nil) (eq x 0))
376 @end example
378 Like the @code{and} construct, @code{or} can be written in terms of
379 @code{cond}.  For example:
381 @example
382 @group
383 (or @var{arg1} @var{arg2} @var{arg3})
384 @equiv{}
385 (cond (@var{arg1})
386       (@var{arg2})
387       (@var{arg3}))
388 @end group
389 @end example
391 You could almost write @code{or} in terms of @code{if}, but not quite:
393 @example
394 @group
395 (if @var{arg1} @var{arg1}
396   (if @var{arg2} @var{arg2} 
397     @var{arg3}))
398 @end group
399 @end example
401 @noindent
402 This is not completely equivalent because it can evaluate @var{arg1} or
403 @var{arg2} twice.  By contrast, @code{(or @var{arg1} @var{arg2}
404 @var{arg3})} never evaluates any argument more than once.
405 @end defspec
407 @node Iteration
408 @section Iteration
409 @cindex iteration
410 @cindex recursion
412   Iteration means executing part of a program repetitively.  For
413 example, you might want to repeat some computation once for each element
414 of a list, or once for each integer from 0 to @var{n}.  You can do this
415 in Emacs Lisp with the special form @code{while}:
417 @defspec while condition forms@dots{}
418 @code{while} first evaluates @var{condition}.  If the result is
419 non-@code{nil}, it evaluates @var{forms} in textual order.  Then it
420 reevaluates @var{condition}, and if the result is non-@code{nil}, it
421 evaluates @var{forms} again.  This process repeats until @var{condition}
422 evaluates to @code{nil}.
424 There is no limit on the number of iterations that may occur.  The loop
425 will continue until either @var{condition} evaluates to @code{nil} or
426 until an error or @code{throw} jumps out of it (@pxref{Nonlocal Exits}).
428 The value of a @code{while} form is always @code{nil}.
430 @example
431 @group
432 (setq num 0)
433      @result{} 0
434 @end group
435 @group
436 (while (< num 4)
437   (princ (format "Iteration %d." num))
438   (setq num (1+ num)))
439      @print{} Iteration 0.
440      @print{} Iteration 1.
441      @print{} Iteration 2.
442      @print{} Iteration 3.
443      @result{} nil
444 @end group
445 @end example
447 If you would like to execute something on each iteration before the
448 end-test, put it together with the end-test in a @code{progn} as the
449 first argument of @code{while}, as shown here:
451 @example
452 @group
453 (while (progn
454          (forward-line 1)
455          (not (looking-at "^$"))))
456 @end group
457 @end example
459 @noindent
460 This moves forward one line and continues moving by lines until it
461 reaches an empty.  It is unusual in that the @code{while} has no body,
462 just the end test (which also does the real work of moving point).
463 @end defspec
465 @node Nonlocal Exits
466 @section Nonlocal Exits
467 @cindex nonlocal exits
469   A @dfn{nonlocal exit} is a transfer of control from one point in a
470 program to another remote point.  Nonlocal exits can occur in Emacs Lisp
471 as a result of errors; you can also use them under explicit control.
472 Nonlocal exits unbind all variable bindings made by the constructs being
473 exited.
475 @menu
476 * Catch and Throw::     Nonlocal exits for the program's own purposes.
477 * Examples of Catch::   Showing how such nonlocal exits can be written.
478 * Errors::              How errors are signaled and handled.
479 * Cleanups::            Arranging to run a cleanup form if an error happens.
480 @end menu
482 @node Catch and Throw
483 @subsection Explicit Nonlocal Exits: @code{catch} and @code{throw}
485   Most control constructs affect only the flow of control within the
486 construct itself.  The function @code{throw} is the exception to this
487 rule of normal program execution: it performs a nonlocal exit on
488 request.  (There are other exceptions, but they are for error handling
489 only.)  @code{throw} is used inside a @code{catch}, and jumps back to
490 that @code{catch}.  For example:
492 @example
493 @group
494 (catch 'foo
495   (progn
496     @dots{}
497     (throw 'foo t)
498     @dots{}))
499 @end group
500 @end example
502 @noindent
503 The @code{throw} transfers control straight back to the corresponding
504 @code{catch}, which returns immediately.  The code following the
505 @code{throw} is not executed.  The second argument of @code{throw} is used
506 as the return value of the @code{catch}.
508   The @code{throw} and the @code{catch} are matched through the first
509 argument: @code{throw} searches for a @code{catch} whose first argument
510 is @code{eq} to the one specified.  Thus, in the above example, the
511 @code{throw} specifies @code{foo}, and the @code{catch} specifies the
512 same symbol, so that @code{catch} is applicable.  If there is more than
513 one applicable @code{catch}, the innermost one takes precedence.
515   Executing @code{throw} exits all Lisp constructs up to the matching
516 @code{catch}, including function calls.  When binding constructs such as
517 @code{let} or function calls are exited in this way, the bindings are
518 unbound, just as they are when these constructs exit normally
519 (@pxref{Local Variables}).  Likewise, @code{throw} restores the buffer
520 and position saved by @code{save-excursion} (@pxref{Excursions}), and
521 the narrowing status saved by @code{save-restriction} and the window
522 selection saved by @code{save-window-excursion} (@pxref{Window
523 Configurations}).  It also runs any cleanups established with the
524 @code{unwind-protect} special form when it exits that form
525 (@pxref{Cleanups}).
527   The @code{throw} need not appear lexically within the @code{catch}
528 that it jumps to.  It can equally well be called from another function
529 called within the @code{catch}.  As long as the @code{throw} takes place
530 chronologically after entry to the @code{catch}, and chronologically
531 before exit from it, it has access to that @code{catch}.  This is why
532 @code{throw} can be used in commands such as @code{exit-recursive-edit}
533 that throw back to the editor command loop (@pxref{Recursive Editing}).
535 @cindex CL note---only @code{throw} in Emacs
536 @quotation
537 @b{Common Lisp note:} Most other versions of Lisp, including Common Lisp,
538 have several ways of transferring control nonsequentially: @code{return},
539 @code{return-from}, and @code{go}, for example.  Emacs Lisp has only
540 @code{throw}.
541 @end quotation
543 @defspec catch tag body@dots{}
544 @cindex tag on run time stack
545 @code{catch} establishes a return point for the @code{throw} function.  The
546 return point is distinguished from other such return points by @var{tag},
547 which may be any Lisp object.  The argument @var{tag} is evaluated normally
548 before the return point is established.
550 With the return point in effect, @code{catch} evaluates the forms of the
551 @var{body} in textual order.  If the forms execute normally, without
552 error or nonlocal exit, the value of the last body form is returned from
553 the @code{catch}.
555 If a @code{throw} is done within @var{body} specifying the same value
556 @var{tag}, the @code{catch} exits immediately; the value it returns is
557 whatever was specified as the second argument of @code{throw}.
558 @end defspec
560 @defun throw tag value
561 The purpose of @code{throw} is to return from a return point previously
562 established with @code{catch}.  The argument @var{tag} is used to choose
563 among the various existing return points; it must be @code{eq} to the value
564 specified in the @code{catch}.  If multiple return points match @var{tag},
565 the innermost one is used.
567 The argument @var{value} is used as the value to return from that
568 @code{catch}.
570 @kindex no-catch
571 If no return point is in effect with tag @var{tag}, then a @code{no-catch}
572 error is signaled with data @code{(@var{tag} @var{value})}.
573 @end defun
575 @node Examples of Catch
576 @subsection Examples of @code{catch} and @code{throw}
578   One way to use @code{catch} and @code{throw} is to exit from a doubly
579 nested loop.  (In most languages, this would be done with a ``go to''.)
580 Here we compute @code{(foo @var{i} @var{j})} for @var{i} and @var{j}
581 varying from 0 to 9:
583 @example
584 @group
585 (defun search-foo ()
586   (catch 'loop
587     (let ((i 0))
588       (while (< i 10)
589         (let ((j 0))
590           (while (< j 10)
591             (if (foo i j)
592                 (throw 'loop (list i j)))
593             (setq j (1+ j))))
594         (setq i (1+ i))))))
595 @end group
596 @end example
598 @noindent
599 If @code{foo} ever returns non-@code{nil}, we stop immediately and return a
600 list of @var{i} and @var{j}.  If @code{foo} always returns @code{nil}, the
601 @code{catch} returns normally, and the value is @code{nil}, since that
602 is the result of the @code{while}.
604   Here are two tricky examples, slightly different, showing two
605 return points at once.  First, two return points with the same tag,
606 @code{hack}:
608 @example
609 @group
610 (defun catch2 (tag)
611   (catch tag
612     (throw 'hack 'yes)))
613 @result{} catch2
614 @end group
616 @group
617 (catch 'hack 
618   (print (catch2 'hack))
619   'no)
620 @print{} yes
621 @result{} no
622 @end group
623 @end example
625 @noindent
626 Since both return points have tags that match the @code{throw}, it goes to
627 the inner one, the one established in @code{catch2}.  Therefore,
628 @code{catch2} returns normally with value @code{yes}, and this value is
629 printed.  Finally the second body form in the outer @code{catch}, which is
630 @code{'no}, is evaluated and returned from the outer @code{catch}.
632   Now let's change the argument given to @code{catch2}:
634 @example
635 @group
636 (defun catch2 (tag)
637   (catch tag
638     (throw 'hack 'yes)))
639 @result{} catch2
640 @end group
642 @group
643 (catch 'hack
644   (print (catch2 'quux))
645   'no)
646 @result{} yes
647 @end group
648 @end example
650 @noindent
651 We still have two return points, but this time only the outer one has
652 the tag @code{hack}; the inner one has the tag @code{quux} instead.
653 Therefore, @code{throw} makes the outer @code{catch} return the value
654 @code{yes}.  The function @code{print} is never called, and the
655 body-form @code{'no} is never evaluated.
657 @node Errors
658 @subsection Errors
659 @cindex errors
661   When Emacs Lisp attempts to evaluate a form that, for some reason,
662 cannot be evaluated, it @dfn{signals} an @dfn{error}.
664   When an error is signaled, Emacs's default reaction is to print an
665 error message and terminate execution of the current command.  This is
666 the right thing to do in most cases, such as if you type @kbd{C-f} at
667 the end of the buffer.
669   In complicated programs, simple termination may not be what you want.
670 For example, the program may have made temporary changes in data
671 structures, or created temporary buffers that should be deleted before
672 the program is finished.  In such cases, you would use
673 @code{unwind-protect} to establish @dfn{cleanup expressions} to be
674 evaluated in case of error.  (@xref{Cleanups}.)  Occasionally, you may
675 wish the program to continue execution despite an error in a subroutine.
676 In these cases, you would use @code{condition-case} to establish
677 @dfn{error handlers} to recover control in case of error.
679   Resist the temptation to use error handling to transfer control from
680 one part of the program to another; use @code{catch} and @code{throw}
681 instead.  @xref{Catch and Throw}.
683 @menu
684 * Signaling Errors::      How to report an error.
685 * Processing of Errors::  What Emacs does when you report an error.
686 * Handling Errors::       How you can trap errors and continue execution.
687 * Error Symbols::         How errors are classified for trapping them.
688 @end menu
690 @node Signaling Errors
691 @subsubsection How to Signal an Error
692 @cindex signaling errors
694   Most errors are signaled ``automatically'' within Lisp primitives
695 which you call for other purposes, such as if you try to take the
696 @sc{car} of an integer or move forward a character at the end of the
697 buffer; you can also signal errors explicitly with the functions
698 @code{error} and @code{signal}.
700   Quitting, which happens when the user types @kbd{C-g}, is not 
701 considered an error, but it is handled almost like an error.
702 @xref{Quitting}.
704 @defun error format-string &rest args
705 This function signals an error with an error message constructed by
706 applying @code{format} (@pxref{String Conversion}) to
707 @var{format-string} and @var{args}.
709 These examples show typical uses of @code{error}:
711 @example
712 @group
713 (error "You have committed an error.  
714         Try something else.")
715      @error{} You have committed an error.  
716         Try something else.
717 @end group
719 @group
720 (error "You have committed %d errors." 10)
721      @error{} You have committed 10 errors.  
722 @end group
723 @end example
725 @code{error} works by calling @code{signal} with two arguments: the
726 error symbol @code{error}, and a list containing the string returned by
727 @code{format}.
729 If you want to use your own string as an error message verbatim, don't
730 just write @code{(error @var{string})}.  If @var{string} contains
731 @samp{%}, it will be interpreted as a format specifier, with undesirable
732 results.  Instead, use @code{(error "%s" @var{string})}.
733 @end defun
735 @defun signal error-symbol data
736 This function signals an error named by @var{error-symbol}.  The
737 argument @var{data} is a list of additional Lisp objects relevant to the
738 circumstances of the error.
740 The argument @var{error-symbol} must be an @dfn{error symbol}---a symbol
741 bearing a property @code{error-conditions} whose value is a list of
742 condition names.  This is how Emacs Lisp classifies different sorts of
743 errors.
745 The number and significance of the objects in @var{data} depends on
746 @var{error-symbol}.  For example, with a @code{wrong-type-arg} error,
747 there are two objects in the list: a predicate that describes the type
748 that was expected, and the object that failed to fit that type.
749 @xref{Error Symbols}, for a description of error symbols.
751 Both @var{error-symbol} and @var{data} are available to any error
752 handlers that handle the error: @code{condition-case} binds a local
753 variable to a list of the form @code{(@var{error-symbol} .@:
754 @var{data})} (@pxref{Handling Errors}).  If the error is not handled,
755 these two values are used in printing the error message.
757 The function @code{signal} never returns (though in older Emacs versions
758 it could sometimes return).
760 @smallexample
761 @group
762 (signal 'wrong-number-of-arguments '(x y))
763      @error{} Wrong number of arguments: x, y
764 @end group
766 @group
767 (signal 'no-such-error '("My unknown error condition."))
768      @error{} peculiar error: "My unknown error condition."
769 @end group
770 @end smallexample
771 @end defun
773 @cindex CL note---no continuable errors
774 @quotation
775 @b{Common Lisp note:} Emacs Lisp has nothing like the Common Lisp
776 concept of continuable errors.
777 @end quotation
779 @node Processing of Errors
780 @subsubsection How Emacs Processes Errors
782 When an error is signaled, @code{signal} searches for an active
783 @dfn{handler} for the error.  A handler is a sequence of Lisp
784 expressions designated to be executed if an error happens in part of the
785 Lisp program.  If the error has an applicable handler, the handler is
786 executed, and control resumes following the handler.  The handler
787 executes in the environment of the @code{condition-case} that
788 established it; all functions called within that @code{condition-case}
789 have already been exited, and the handler cannot return to them.
791 If there is no applicable handler for the error, the current command is
792 terminated and control returns to the editor command loop, because the
793 command loop has an implicit handler for all kinds of errors.  The
794 command loop's handler uses the error symbol and associated data to
795 print an error message.
797 @cindex @code{debug-on-error} use
798 An error that has no explicit handler may call the Lisp debugger.  The
799 debugger is enabled if the variable @code{debug-on-error} (@pxref{Error
800 Debugging}) is non-@code{nil}.  Unlike error handlers, the debugger runs
801 in the environment of the error, so that you can examine values of
802 variables precisely as they were at the time of the error.
804 @node Handling Errors
805 @subsubsection Writing Code to Handle Errors
806 @cindex error handler
807 @cindex handling errors
809   The usual effect of signaling an error is to terminate the command
810 that is running and return immediately to the Emacs editor command loop.
811 You can arrange to trap errors occurring in a part of your program by
812 establishing an error handler, with the special form
813 @code{condition-case}.  A simple example looks like this:
815 @example
816 @group
817 (condition-case nil
818     (delete-file filename)
819   (error nil))
820 @end group
821 @end example
823 @noindent
824 This deletes the file named @var{filename}, catching any error and
825 returning @code{nil} if an error occurs.
827   The second argument of @code{condition-case} is called the
828 @dfn{protected form}.  (In the example above, the protected form is a
829 call to @code{delete-file}.)  The error handlers go into effect when
830 this form begins execution and are deactivated when this form returns.
831 They remain in effect for all the intervening time.  In particular, they
832 are in effect during the execution of functions called by this form, in
833 their subroutines, and so on.  This is a good thing, since, strictly
834 speaking, errors can be signaled only by Lisp primitives (including
835 @code{signal} and @code{error}) called by the protected form, not by the
836 protected form itself.
838   The arguments after the protected form are handlers.  Each handler
839 lists one or more @dfn{condition names} (which are symbols) to specify
840 which errors it will handle.  The error symbol specified when an error
841 is signaled also defines a list of condition names.  A handler applies
842 to an error if they have any condition names in common.  In the example
843 above, there is one handler, and it specifies one condition name,
844 @code{error}, which covers all errors.
846   The search for an applicable handler checks all the established handlers
847 starting with the most recently established one.  Thus, if two nested
848 @code{condition-case} forms offer to handle the same error, the inner of
849 the two will actually handle it.
851   When an error is handled, control returns to the handler.  Before this
852 happens, Emacs unbinds all variable bindings made by binding constructs
853 that are being exited and executes the cleanups of all
854 @code{unwind-protect} forms that are exited.  Once control arrives at
855 the handler, the body of the handler is executed.
857   After execution of the handler body, execution returns from the
858 @code{condition-case} form.  Because the protected form is exited
859 completely before execution of the handler, the handler cannot resume
860 execution at the point of the error, nor can it examine variable
861 bindings that were made within the protected form.  All it can do is
862 clean up and proceed.
864   @code{condition-case} is often used to trap errors that are
865 predictable, such as failure to open a file in a call to
866 @code{insert-file-contents}.  It is also used to trap errors that are
867 totally unpredictable, such as when the program evaluates an expression
868 read from the user.
870   Error signaling and handling have some resemblance to @code{throw} and
871 @code{catch}, but they are entirely separate facilities.  An error
872 cannot be caught by a @code{catch}, and a @code{throw} cannot be handled
873 by an error handler (though using @code{throw} when there is no suitable
874 @code{catch} signals an error that can be handled).
876 @defspec condition-case var protected-form handlers@dots{}
877 This special form establishes the error handlers @var{handlers} around
878 the execution of @var{protected-form}.  If @var{protected-form} executes
879 without error, the value it returns becomes the value of the
880 @code{condition-case} form; in this case, the @code{condition-case} has
881 no effect.  The @code{condition-case} form makes a difference when an
882 error occurs during @var{protected-form}.
884 Each of the @var{handlers} is a list of the form @code{(@var{conditions}
885 @var{body}@dots{})}.  Here @var{conditions} is an error condition name
886 to be handled, or a list of condition names; @var{body} is one or more
887 Lisp expressions to be executed when this handler handles an error.
888 Here are examples of handlers:
890 @smallexample
891 @group
892 (error nil)
894 (arith-error (message "Division by zero"))
896 ((arith-error file-error)
897  (message
898   "Either division by zero or failure to open a file"))
899 @end group
900 @end smallexample
902 Each error that occurs has an @dfn{error symbol} that describes what
903 kind of error it is.  The @code{error-conditions} property of this
904 symbol is a list of condition names (@pxref{Error Symbols}).  Emacs
905 searches all the active @code{condition-case} forms for a handler that
906 specifies one or more of these condition names; the innermost matching
907 @code{condition-case} handles the error.  Within this
908 @code{condition-case}, the first applicable handler handles the error.
910 After executing the body of the handler, the @code{condition-case}
911 returns normally, using the value of the last form in the handler body
912 as the overall value.
914 @cindex error description
915 The argument @var{var} is a variable.  @code{condition-case} does not
916 bind this variable when executing the @var{protected-form}, only when it
917 handles an error.  At that time, it binds @var{var} locally to an
918 @dfn{error description}, which is a list giving the particulars of the
919 error.  The error description has the form @code{(@var{error-symbol}
920 . @var{data})}.  The handler can refer to this list to decide what to
921 do.  For example, if the error is for failure opening a file, the file
922 name is the second element of @var{data}---the third element of the
923 error description.
925 If @var{var} is @code{nil}, that means no variable is bound.  Then the
926 error symbol and associated data are not available to the handler.
927 @end defspec
929 @defun error-message-string error-description
930 This function returns the error message string for a given error
931 descriptor.  It is useful if you want to handle an error by printing the
932 usual error message for that error.
933 @end defun
935 @cindex @code{arith-error} example
936 Here is an example of using @code{condition-case} to handle the error
937 that results from dividing by zero.  The handler displays the error
938 message (but without a beep), then returns a very large number.
940 @smallexample
941 @group
942 (defun safe-divide (dividend divisor)
943   (condition-case err                
944       ;; @r{Protected form.}
945       (/ dividend divisor)              
946     ;; @r{The handler.}
947     (arith-error                        ; @r{Condition.}
948      ;; @r{Display the usual message for this error.}
949      (message "%s" (error-message-string err))
950      1000000)))
951 @result{} safe-divide
952 @end group
954 @group
955 (safe-divide 5 0)
956      @print{} Arithmetic error: (arith-error)
957 @result{} 1000000
958 @end group
959 @end smallexample
961 @noindent
962 The handler specifies condition name @code{arith-error} so that it will handle only division-by-zero errors.  Other kinds of errors will not be handled, at least not by this @code{condition-case}.  Thus,
964 @smallexample
965 @group
966 (safe-divide nil 3)
967      @error{} Wrong type argument: integer-or-marker-p, nil
968 @end group
969 @end smallexample
971   Here is a @code{condition-case} that catches all kinds of errors,
972 including those signaled with @code{error}:
974 @smallexample
975 @group
976 (setq baz 34)
977      @result{} 34
978 @end group
980 @group
981 (condition-case err
982     (if (eq baz 35)
983         t
984       ;; @r{This is a call to the function @code{error}.}
985       (error "Rats!  The variable %s was %s, not 35" 'baz baz))
986   ;; @r{This is the handler; it is not a form.}
987   (error (princ (format "The error was: %s" err)) 
988          2))
989 @print{} The error was: (error "Rats!  The variable baz was 34, not 35")
990 @result{} 2
991 @end group
992 @end smallexample
994 @node Error Symbols
995 @subsubsection Error Symbols and Condition Names
996 @cindex error symbol
997 @cindex error name
998 @cindex condition name
999 @cindex user-defined error
1000 @kindex error-conditions
1002   When you signal an error, you specify an @dfn{error symbol} to specify
1003 the kind of error you have in mind.  Each error has one and only one
1004 error symbol to categorize it.  This is the finest classification of
1005 errors defined by the Emacs Lisp language.
1007   These narrow classifications are grouped into a hierarchy of wider
1008 classes called @dfn{error conditions}, identified by @dfn{condition
1009 names}.  The narrowest such classes belong to the error symbols
1010 themselves: each error symbol is also a condition name.  There are also
1011 condition names for more extensive classes, up to the condition name
1012 @code{error} which takes in all kinds of errors.  Thus, each error has
1013 one or more condition names: @code{error}, the error symbol if that
1014 is distinct from @code{error}, and perhaps some intermediate
1015 classifications.
1017   In order for a symbol to be an error symbol, it must have an
1018 @code{error-conditions} property which gives a list of condition names.
1019 This list defines the conditions that this kind of error belongs to.
1020 (The error symbol itself, and the symbol @code{error}, should always be
1021 members of this list.)  Thus, the hierarchy of condition names is
1022 defined by the @code{error-conditions} properties of the error symbols.
1024   In addition to the @code{error-conditions} list, the error symbol
1025 should have an @code{error-message} property whose value is a string to
1026 be printed when that error is signaled but not handled.  If the
1027 @code{error-message} property exists, but is not a string, the error
1028 message @samp{peculiar error} is used.
1029 @cindex peculiar error
1031   Here is how we define a new error symbol, @code{new-error}:
1033 @example
1034 @group
1035 (put 'new-error
1036      'error-conditions
1037      '(error my-own-errors new-error))       
1038 @result{} (error my-own-errors new-error)
1039 @end group
1040 @group
1041 (put 'new-error 'error-message "A new error")
1042 @result{} "A new error"
1043 @end group
1044 @end example
1046 @noindent
1047 This error has three condition names: @code{new-error}, the narrowest
1048 classification; @code{my-own-errors}, which we imagine is a wider
1049 classification; and @code{error}, which is the widest of all.
1051   The error string should start with a capital letter but it should
1052 not end with a period.  This is for consistency with the rest of Emacs.
1054   Naturally, Emacs will never signal @code{new-error} on its own; only
1055 an explicit call to @code{signal} (@pxref{Signaling Errors}) in your
1056 code can do this:
1058 @example
1059 @group
1060 (signal 'new-error '(x y))
1061      @error{} A new error: x, y
1062 @end group
1063 @end example
1065   This error can be handled through any of the three condition names.
1066 This example handles @code{new-error} and any other errors in the class
1067 @code{my-own-errors}:
1069 @example
1070 @group
1071 (condition-case foo
1072     (bar nil t)
1073   (my-own-errors nil))
1074 @end group
1075 @end example
1077   The significant way that errors are classified is by their condition
1078 names---the names used to match errors with handlers.  An error symbol
1079 serves only as a convenient way to specify the intended error message
1080 and list of condition names.  It would be cumbersome to give
1081 @code{signal} a list of condition names rather than one error symbol.
1083   By contrast, using only error symbols without condition names would
1084 seriously decrease the power of @code{condition-case}.  Condition names
1085 make it possible to categorize errors at various levels of generality
1086 when you write an error handler.  Using error symbols alone would
1087 eliminate all but the narrowest level of classification.
1089   @xref{Standard Errors}, for a list of all the standard error symbols
1090 and their conditions.
1092 @node Cleanups
1093 @subsection Cleaning Up from Nonlocal Exits
1095   The @code{unwind-protect} construct is essential whenever you
1096 temporarily put a data structure in an inconsistent state; it permits
1097 you to ensure the data are consistent in the event of an error or throw.
1099 @defspec unwind-protect body cleanup-forms@dots{}
1100 @cindex cleanup forms
1101 @cindex protected forms
1102 @cindex error cleanup
1103 @cindex unwinding
1104 @code{unwind-protect} executes the @var{body} with a guarantee that the
1105 @var{cleanup-forms} will be evaluated if control leaves @var{body}, no
1106 matter how that happens.  The @var{body} may complete normally, or
1107 execute a @code{throw} out of the @code{unwind-protect}, or cause an
1108 error; in all cases, the @var{cleanup-forms} will be evaluated.
1110 If the @var{body} forms finish normally, @code{unwind-protect} returns
1111 the value of the last @var{body} form, after it evaluates the
1112 @var{cleanup-forms}.  If the @var{body} forms do not finish,
1113 @code{unwind-protect} does not return any value in the normal sense.
1115 Only the @var{body} is actually protected by the @code{unwind-protect}.
1116 If any of the @var{cleanup-forms} themselves exits nonlocally (e.g., via
1117 a @code{throw} or an error), @code{unwind-protect} is @emph{not}
1118 guaranteed to evaluate the rest of them.  If the failure of one of the
1119 @var{cleanup-forms} has the potential to cause trouble, then protect it
1120 with another @code{unwind-protect} around that form.
1122 The number of currently active @code{unwind-protect} forms counts,
1123 together with the number of local variable bindings, against the limit
1124 @code{max-specpdl-size} (@pxref{Local Variables}).
1125 @end defspec
1127   For example, here we make an invisible buffer for temporary use, and
1128 make sure to kill it before finishing:
1130 @smallexample
1131 @group
1132 (save-excursion
1133   (let ((buffer (get-buffer-create " *temp*")))
1134     (set-buffer buffer)
1135     (unwind-protect
1136         @var{body}
1137       (kill-buffer buffer))))
1138 @end group
1139 @end smallexample
1141 @noindent
1142 You might think that we could just as well write @code{(kill-buffer
1143 (current-buffer))} and dispense with the variable @code{buffer}.
1144 However, the way shown above is safer, if @var{body} happens to get an
1145 error after switching to a different buffer!  (Alternatively, you could
1146 write another @code{save-excursion} around the body, to ensure that the
1147 temporary buffer becomes current in time to kill it.)
1149 @findex ftp-login
1150   Here is an actual example taken from the file @file{ftp.el}.  It
1151 creates a process (@pxref{Processes}) to try to establish a connection
1152 to a remote machine.  As the function @code{ftp-login} is highly
1153 susceptible to numerous problems that the writer of the function cannot
1154 anticipate, it is protected with a form that guarantees deletion of the
1155 process in the event of failure.  Otherwise, Emacs might fill up with
1156 useless subprocesses.
1158 @smallexample
1159 @group
1160 (let ((win nil))
1161   (unwind-protect
1162       (progn
1163         (setq process (ftp-setup-buffer host file))
1164         (if (setq win (ftp-login process host user password))
1165             (message "Logged in")
1166           (error "Ftp login failed")))
1167     (or win (and process (delete-process process)))))
1168 @end group
1169 @end smallexample
1171   This example actually has a small bug: if the user types @kbd{C-g} to
1172 quit, and the quit happens immediately after the function
1173 @code{ftp-setup-buffer} returns but before the variable @code{process} is
1174 set, the process will not be killed.  There is no easy way to fix this bug,
1175 but at least it is very unlikely.
1177   Here is another example which uses @code{unwind-protect} to make sure
1178 to kill a temporary buffer.  In this example, the value returned by
1179 @code{unwind-protect} is used.
1181 @smallexample
1182 (defun shell-command-string (cmd)
1183   "Return the output of the shell command CMD, as a string."
1184   (save-excursion
1185     (set-buffer (generate-new-buffer " OS*cmd"))
1186     (shell-command cmd t)
1187     (unwind-protect
1188         (buffer-string)
1189       (kill-buffer (current-buffer)))))
1190 @end smallexample