Initial git import
[sxemacs] / info / lispref / control.texi
1 @c -*-texinfo-*-
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
7
8 @node Control Structures, Variables, Evaluation, Top
9 @chapter Control Structures
10 @cindex special forms for control structures
11 @cindex control structures
12
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
17 contain.
18
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}.
27
28   Explicit control structures make possible an order of execution other
29 than sequential.
30
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}).
37
38 @menu
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.
44 @end menu
45
46
47 @node Sequencing
48 @section Sequencing
49
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.
55
56   A @code{progn} special form looks like this:
57
58 @example
59 @group
60 (progn @var{a} @var{b} @var{c} @dots{})
61 @end group
62 @end example
63
64 @noindent
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
68 @code{progn}.
69
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}.
81
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.
85
86 @example
87 @group
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"
95 @end group
96 @end example
97 @end defspec
98
99   Two other control constructs likewise evaluate a series of forms but return
100 a different value:
101
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}.
105
106 @example
107 @group
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"
115 @end group
116 @end example
117
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:
120
121 @example
122 (prog1 (car x) (setq x (cdr x)))
123 @end example
124 @end defspec
125
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
129 @var{form2}.
130
131 @example
132 @group
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"
140 @end group
141 @end example
142 @end defspec
143
144
145 @node Conditionals
146 @section Conditionals
147 @cindex conditional evaluation
148
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
152 statement.
153
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}.)
161
162 If @var{condition} has the value @code{nil}, and no @var{else-forms} are
163 given, @code{if} returns @code{nil}.
164
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.
168
169 @example
170 @group
171 (if nil
172     (print 'true)
173   'very-false)
174 @result{} very-false
175 @end group
176 @end example
177 @end defspec
178
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:
184
185 @example
186 (@var{condition} @var{body-forms}@dots{})
187 @end example
188
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.
194
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
197 @var{condition}.
198
199 If every @var{condition} evaluates to @code{nil}, so that every clause
200 fails, @code{cond} returns @code{nil}.
201
202 A clause may also look like this:
203
204 @example
205 (@var{condition})
206 @end example
207
208 @noindent
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.
211
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,
214 respectively:
215
216 @example
217 @group
218 (cond ((numberp x) x)
219       ((stringp x) x)
220       ((bufferp x)
221        (setq temporary-hack x) ; @r{multiple body-forms}
222        (buffer-name x))        ; @r{in one clause}
223       ((symbolp x) (symbol-value x)))
224 @end group
225 @end example
226
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}
232 gets to it at all.
233
234 For example,
235
236 @example
237 @group
238 (cond ((eq a 'hack) 'foo)
239       (t "default"))
240 @result{} "default"
241 @end group
242 @end example
243
244 @noindent
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.
247 @end defspec
248
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.
251 For example:
252
253 @example
254 @group
255 (if @var{a} @var{b} @var{c})
256 @equiv{}
257 (cond (@var{a} @var{b}) (t @var{c}))
258 @end group
259 @end example
260
261
262 @node Combining Conditions
263 @section Constructs for Combining Conditions
264
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.
269
270 @defun not condition
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.
275 @end defun
276
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
280 order written.
281
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}.
286
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.
289
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.
294
295 @example
296 @group
297 (and (print 1) (print 2) nil (print 3))
298      @print{} 1
299      @print{} 2
300 @result{} nil
301 @end group
302 @end example
303
304 Here is a more realistic example of using @code{and}:
305
306 @example
307 @group
308 (if (and (consp foo) (eq (car foo) 'x))
309     (message "foo is a list starting with x"))
310 @end group
311 @end example
312
313 @noindent
314 Note that @code{(car foo)} is not executed if @code{(consp foo)} returns
315 @code{nil}, thus avoiding an error.
316
317 @code{and} can be expressed in terms of either @code{if} or @code{cond}.
318 For example:
319
320 @example
321 @group
322 (and @var{arg1} @var{arg2} @var{arg3})
323 @equiv{}
324 (if @var{arg1} (if @var{arg2} @var{arg3}))
325 @equiv{}
326 (cond (@var{arg1} (cond (@var{arg2} @var{arg3}))))
327 @end group
328 @end example
329 @end defspec
330
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.
335
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.
340
341 If all the @var{conditions} turn out @code{nil}, then the @code{or}
342 expression returns @code{nil}.
343
344 For example, this expression tests whether @code{x} is either 0 or
345 @code{nil}:
346
347 @example
348 (or (eq x nil) (eq x 0))
349 @end example
350
351 Like the @code{and} construct, @code{or} can be written in terms of
352 @code{cond}.  For example:
353
354 @example
355 @group
356 (or @var{arg1} @var{arg2} @var{arg3})
357 @equiv{}
358 (cond (@var{arg1})
359       (@var{arg2})
360       (@var{arg3}))
361 @end group
362 @end example
363
364 You could almost write @code{or} in terms of @code{if}, but not quite:
365
366 @example
367 @group
368 (if @var{arg1} @var{arg1}
369   (if @var{arg2} @var{arg2}
370     @var{arg3}))
371 @end group
372 @end example
373
374 @noindent
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.
378 @end defspec
379
380
381 @node Iteration
382 @section Iteration
383 @cindex iteration
384 @cindex recursion
385
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}:
390
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}.
397
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}).
401
402 The value of a @code{while} form is always @code{nil}.
403
404 @example
405 @group
406 (setq num 0)
407      @result{} 0
408 @end group
409 @group
410 (while (< num 4)
411   (princ (format "Iteration %d." num))
412   (setq num (1+ num)))
413      @print{} Iteration 0.
414      @print{} Iteration 1.
415      @print{} Iteration 2.
416      @print{} Iteration 3.
417      @result{} nil
418 @end group
419 @end example
420
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:
424
425 @example
426 @group
427 (while (progn
428          (forward-line 1)
429          (not (looking-at "^$"))))
430 @end group
431 @end example
432
433 @noindent
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).
437 @end defspec
438
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
441 loaded.
442 @c description here anyway?
443
444
445 @node Nonlocal Exits
446 @section Nonlocal Exits
447 @cindex nonlocal exits
448
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.
454
455 @menu
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.
460 @end menu
461
462
463 @node Catch and Throw
464 @subsection Explicit Nonlocal Exits: @code{catch} and @code{throw}
465
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:
472
473 @example
474 @group
475 (catch 'foo
476   (progn
477     @dots{}
478     (throw 'foo t)
479     @dots{}))
480 @end group
481 @end example
482
483 @noindent
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}.
488
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.
495
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
506 (@pxref{Cleanups}).
507
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}).
515
516 @cindex CL note---only @code{throw} in SXEmacs
517 @quotation
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
521 @code{throw}.
522 @end quotation
523
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.
530
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
534 the @code{catch}.
535
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}.
539 @end defspec
540
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.
547
548 The argument @var{value} is used as the value to return from that
549 @code{catch}.
550
551 @kindex no-catch
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})}.
554 @end defun
555
556
557 @node Examples of Catch
558 @subsection Examples of @code{catch} and @code{throw}
559
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}
563 varying from 0 to 9:
564
565 @example
566 @group
567 (defun search-foo ()
568   (catch 'loop
569     (let ((i 0))
570       (while (< i 10)
571         (let ((j 0))
572           (while (< j 10)
573             (if (foo i j)
574                 (throw 'loop (list i j)))
575             (setq j (1+ j))))
576         (setq i (1+ i))))))
577 @end group
578 @end example
579
580 @noindent
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}.
585
586   Here are two tricky examples, slightly different, showing two
587 return points at once.  First, two return points with the same tag,
588 @code{hack}:
589
590 @example
591 @group
592 (defun catch2 (tag)
593   (catch tag
594     (throw 'hack 'yes)))
595 @result{} catch2
596 @end group
597
598 @group
599 (catch 'hack
600   (print (catch2 'hack))
601   'no)
602 @print{} yes
603 @result{} no
604 @end group
605 @end example
606
607 @noindent
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}.
613
614   Now let's change the argument given to @code{catch2}:
615
616 @example
617 @group
618 (defun catch2 (tag)
619   (catch tag
620     (throw 'hack 'yes)))
621 @result{} catch2
622 @end group
623
624 @group
625 (catch 'hack
626   (print (catch2 'quux))
627   'no)
628 @result{} yes
629 @end group
630 @end example
631
632 @noindent
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.
638
639
640 @node Errors
641 @subsection Errors
642 @cindex errors
643
644   When SXEmacs Lisp attempts to evaluate a form that, for some reason,
645 cannot be evaluated, it @dfn{signals} an @dfn{error}.
646
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.
651
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}.)
658
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.
663
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}.
667
668 @menu
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.
673 @end menu
674
675
676 @node Signaling Errors
677 @subsubsection How to Signal an Error
678 @cindex signaling errors
679
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.
685
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.
688 @xref{Quitting}.
689
690 SXEmacs has a rich hierarchy of error symbols predefined via
691 @code{deferror}.
692
693 @example
694 error
695   syntax-error
696     invalid-read-syntax
697     list-formation-error
698       malformed-list
699         malformed-property-list
700       circular-list
701         circular-property-list
702
703   invalid-argument
704     wrong-type-argument
705     args-out-of-range
706     wrong-number-of-arguments
707     invalid-function
708     no-catch
709
710   invalid-state
711     void-function
712     cyclic-function-indirection
713     void-variable
714     cyclic-variable-indirection
715
716   invalid-operation
717     invalid-change
718       setting-constant
719     editing-error
720       beginning-of-buffer
721       end-of-buffer
722       buffer-read-only
723     io-error
724       end-of-file
725     arith-error
726       range-error
727       domain-error
728       singularity-error
729       overflow-error
730       underflow-error
731 @end example
732
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:
737
738 @itemize @bullet
739 @item
740 @code{syntax-error} is for errors in complex structures: parsed strings,
741 lists, and the like.
742
743 @item
744 @code{invalid-argument} is for errors in a simple value.  Typically, the
745 entire value, not just one part of it, is wrong.
746
747 @item
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
752 error:
753
754 @item
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}.
758
759 @item
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.
764 @end itemize
765
766 @defun error datum &rest args
767 This function signals a non-continuable error.
768
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.
773
774 This error is not continuable: you cannot continue execution after the
775 error using the debugger @kbd{r} command.  See also @code{cerror}.
776
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.:
784
785 @itemize @bullet
786 @item
787 the buffer in which an editing error occurred.
788 @item
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.)
796 @item
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.
801 @end itemize
802
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
809 to use.
810
811 See also @code{cerror}, @code{signal}, and @code{signal-error}."
812
813 These examples show typical uses of @code{error}:
814
815 @example
816 @group
817 (error 'syntax-error
818        "Dialog descriptor must supply at least one button"
819         descriptor)
820 @end group
821
822 @group
823 (error "You have committed an error.
824         Try something else.")
825      @error{} You have committed an error.
826         Try something else.
827 @end group
828
829 @group
830 (error "You have committed %d errors." 10)
831      @error{} You have committed 10 errors.
832 @end group
833 @end example
834
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})}.
839 @end defun
840
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.
845 @end defun
846
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.
851
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
855 errors.
856
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.
862
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.
868
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.
872
873 Note: In FSF Emacs @code{signal} never returns.
874
875 @smallexample
876 @group
877 (signal 'wrong-number-of-arguments '(x y))
878      @error{} Wrong number of arguments: x, y
879 @end group
880
881 @group
882 (signal 'no-such-error '("My unknown error condition"))
883      @error{} Peculiar error (no-such-error "My unknown error condition")
884 @end group
885 @end smallexample
886 @end defun
887
888 @defun signal-error error-symbol data
889 This function behaves like @code{signal}, except that the error it
890 signals is not continuable.
891 @end defun
892
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.
900
901 @var{argument} is not evaluated, and should be a symbol.
902 @var{predicate} is evaluated, and should name a function.
903
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
906 proceeding.
907
908 @example
909 @group
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)
914   @dots{})
915 @end group
916 @end example
917 @end defmac
918
919
920 @node Processing of Errors
921 @subsubsection How SXEmacs Processes Errors
922
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.
928
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
932 return to them. 
933
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.
939
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.
944
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, ...}.
952 @end defun
953
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
958 in string form.
959 @end defun
960
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.
967
968
969 @node Handling Errors
970 @subsubsection Writing Code to Handle Errors
971 @cindex error handler
972 @cindex handling errors
973
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:
979
980 @example
981 @group
982 (condition-case nil
983     (delete-file filename)
984   (error nil))
985 @end group
986 @end example
987
988 @noindent
989 This deletes the file named @var{filename}, catching any error and
990 returning @code{nil} if an error occurs.
991
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.
997
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.
1003
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.
1011
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.
1016
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.
1022
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.
1029
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
1034 read from the user.
1035
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.
1042
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).
1048
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}.
1056
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:
1062
1063 @smallexample
1064 @group
1065 (error nil)
1066
1067 (arith-error (message "Division by zero"))
1068
1069 ((arith-error file-error)
1070  (message
1071   "Either division by zero or failure to open a file"))
1072 @end group
1073 @end smallexample
1074
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.
1082
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.
1086
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
1094 @var{var}.
1095
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.
1098 @end defspec
1099
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.
1104
1105 @smallexample
1106 @group
1107 (defun safe-divide (dividend divisor)
1108   (condition-case err
1109       ;; @r{Protected form.}
1110       (/ dividend divisor)
1111     ;; @r{The handler.}
1112     (arith-error                        ; @r{Condition.}
1113      (princ (format "Arithmetic error: %s" err))
1114      1000000)))
1115 @result{} safe-divide
1116 @end group
1117
1118 @group
1119 (safe-divide 5 0)
1120      @print{} Arithmetic error: (arith-error)
1121 @result{} 1000000
1122 @end group
1123 @end smallexample
1124
1125 @noindent
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,
1129
1130 @smallexample
1131 @group
1132 (safe-divide nil 3)
1133      @error{} Wrong type argument: integer-or-marker-p, nil
1134 @end group
1135 @end smallexample
1136
1137   Here is a @code{condition-case} that catches all kinds of errors,
1138 including those signaled with @code{error}:
1139
1140 @smallexample
1141 @group
1142 (setq baz 34)
1143      @result{} 34
1144 @end group
1145
1146 @group
1147 (condition-case err
1148     (if (eq baz 35)
1149         t
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))
1154          2))
1155 @print{} The error was: (error "Rats!  The variable baz was 34, not 35")
1156 @result{} 2
1157 @end group
1158 @end smallexample
1159
1160
1161 @node Error Symbols
1162 @subsubsection Error Symbols and Condition Names
1163 @cindex error symbol
1164 @cindex error name
1165 @cindex condition name
1166 @cindex user-defined error
1167 @kindex error-conditions
1168
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.
1173
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
1182 classifications.
1183
1184   In other words, each error condition @dfn{inherits} from another error
1185 condition, with @code{error} sitting at the top of the inheritance
1186 hierarchy.
1187
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}).
1193
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}.
1198
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}.
1203 @end defun
1204
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}:
1207
1208 @example
1209 @group
1210 (define-error 'my-own-errors "A whole range of errors" 'error)
1211 (define-error 'new-error "A new error" 'my-own-errors)
1212 @end group
1213 @end example
1214
1215 @noindent
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.
1219
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
1223 error.
1224
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.
1227
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
1230 code can do this:
1231
1232 @example
1233 @group
1234 (signal 'new-error '(x y))
1235      @error{} A new error: x, y
1236 @end group
1237 @end example
1238
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}:
1242
1243 @example
1244 @group
1245 (condition-case foo
1246     (bar nil t)
1247   (my-own-errors nil))
1248 @end group
1249 @end example
1250
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.
1256
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.
1262
1263   @xref{Standard Errors}, for a list of all the standard error symbols
1264 and their conditions.
1265
1266
1267 @node Cleanups
1268 @subsection Cleaning Up from Nonlocal Exits
1269
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.
1273
1274 @defspec unwind-protect body cleanup-forms@dots{}
1275 @cindex cleanup forms
1276 @cindex protected forms
1277 @cindex error cleanup
1278 @cindex unwinding
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.
1284
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.
1289
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.
1296
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}).
1300 @end defspec
1301
1302   For example, here we make an invisible buffer for temporary use, and
1303 make sure to kill it before finishing:
1304
1305 @smallexample
1306 @group
1307 (save-excursion
1308   (let ((buffer (get-buffer-create " *temp*")))
1309     (set-buffer buffer)
1310     (unwind-protect
1311         @var{body}
1312       (kill-buffer buffer))))
1313 @end group
1314 @end smallexample
1315
1316 @noindent
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.
1323
1324 @findex ftp-login
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.
1332
1333 @smallexample
1334 @group
1335 (let ((win nil))
1336   (unwind-protect
1337       (progn
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)))))
1343 @end group
1344 @end smallexample
1345
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.
1351
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.
1355
1356 @smallexample
1357 (defun shell-command-string (cmd)
1358   "Return the output of the shell command CMD, as a string."
1359   (save-excursion
1360     (set-buffer (generate-new-buffer " OS*cmd"))
1361     (shell-command cmd t)
1362     (unwind-protect
1363         (buffer-string)
1364       (kill-buffer (current-buffer)))))
1365 @end smallexample