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