DataMuseum.dk

Presents historical artifacts from the history of:

DKUUG/EUUG Conference tapes

This is an automatic "excavation" of a thematic subset of
artifacts from Datamuseum.dk's BitArchive.

See our Wiki for more about DKUUG/EUUG Conference tapes

Excavated with: AutoArchaeologist - Free & Open Source Software.


top - metrics - download
Index: T c

⟦7d4609f25⟧ TextFile

    Length: 38630 (0x96e6)
    Types: TextFile
    Names: »control.texinfo«

Derivation

└─⟦a05ed705a⟧ Bits:30007078 DKUUG GNU 2/12/89
    └─⟦c06c473ab⟧ »./UNRELEASED/lispref.tar.Z« 
        └─⟦1b57a2ffe⟧ 
            └─⟦this⟧ »control.texinfo« 

TextFile

@setfilename ../info/control
@node Control Structures, Evaluation, Macros, Top
@chapter Control Structures

@cindex special form evaluation
  A Lisp program consists of expressions or @dfn{forms} (@pxref{Forms}).
We control the order of execution of the forms by enclosing them in
@dfn{control structures}.  Control structures are special forms which
control when, whether, or how many times to execute the forms they contain.

  The simplest control structure is sequential execution: first form
@var{a}, then form @var{b}, and so on.  This is what happens when you write
several forms in succession in the body of a function, or at top level in a
file of Lisp code.  The forms are executed in the order they are written.
We call this @dfn{textual order}.  For example, if a function body
consists of two forms @var{a} and @var{b}, evaluation of the function
causes @var{a} to be evaluated before @var{b}, and the result is the value
of @var{b}.

  Naturally, Emacs Lisp has other kinds of control structures, including
other varieties of sequencing, function calls, conditionals, iteration,
and (controlled) jumps.  These control structures are special forms
since their subforms are not necessarily evaluated.  You can use macros
to define your own control structure constructs (@pxref{Macros}).

@menu
* Sequencing::          Evaluation in textual order.
* Conditionals::        if, cond.
* Combining Conditions:: and, or, not.
* Iteration::           while.
* Nonlocal Exits::      Jumping out of a sequence.
* Beeping::             Audible signal to user
@end menu

@node Sequencing, Conditionals, Control Structures, Control Structures
@section Sequencing

  Evaluating forms in the order they are written is the most common
control structure.  Sometimes this happens automatically, such as in a
function body.  Elsewhere you must use a control structure construct to
do this: @code{progn}, the simplest control construct of Lisp.

  A @code{progn} special form looks like this:

@example
(progn @var{a} @var{b} @var{c} @dots{})
@end example

@noindent
and it says to execute the forms @var{a}, @var{b}, @var{c} and so on, in
that order.  These forms are called the body of the @code{progn} form.
The result of the last form in the body becomes the result of the entire
@code{progn}.

  When Lisp was young, @code{progn} was the only way to execute two or
more forms in succession and use the value of the last of them.  But
programmers found they often needed to use a @code{progn} in the body of
a function, where (at that time) only one form was allowed.  So the body
of a function was made into an ``implicit @code{progn}'': several forms
are allowed just as in the body of an actual @code{progn}.  Many other
control structures likewise contain an implicit @code{progn}.  As a
result, @code{progn} is not used as often as it used to be.  It is
needed now most often inside of an @code{unwind-protect}, @code{and} or
@code{or}.

@defspec progn forms@dots{}
This special form evaluates all of the @var{forms}, in textual
order, returning the result of the final form.

@example
(progn (print "The first form")
       (print "The second form")
       (print "The third form"))
     @print{} "The first form"
     @print{} "The second form"
     @print{} "The third form"
     @result{} "The third form"
@end example
@end defspec

  Two other control constructs likewise evaluate a series of forms but return
a different value:

@defspec prog1 form1 forms@dots{}
This special form evaluates @var{form1} and all of the @var{forms}, in
textual order, returning the result of the first form.

@example
(prog1 (print "The first form")
       (print "The second form")
       (print "The third form"))
     @print{} "The first form"
     @print{} "The second form"
     @print{} "The third form"
     @result{} "The first form"
@end example

Here is a way to remove the first element from a list in the variable
@code{x}, then go ahead and use that element:

@example
(foo (prog1 (car x) (setq x (cdr x))))
@end example
@end defspec

@defspec prog2 form1 form2 forms@dots{}
This special form evaluates @var{form1}, @var{form2}, and all of the
following @var{forms}, in textual order, returning the result of the
second form.

@example
(prog2 (print "The first form")
       (print "The second form")
       (print "The third form"))
     @print{} "The first form"
     @print{} "The second form"
     @print{} "The third form"
     @result{} "The second form"
@end example
@end defspec

@node Conditionals, Combining Conditions, Sequencing, Control Structures
@section Conditionals
@cindex conditional evaluation

  Conditional control structures choose among alternatives.  Emacs Lisp
has two conditional forms: @code{if}, which is much the same as in other
languages, and @code{cond}, which is a generalized case statement.

@defspec if condition then-form else-forms@dots{}
@code{if} chooses between the @var{then-form} and the @var{else-forms}
based on the value of @var{condition}.  If the evaluated @var{condition} is
non-@code{nil}, @var{then-form} is evaluated and the result returned.
Otherwise, the @var{else-forms} are evaluated in textual order, and the
value of the last one is returned.  (The @var{else} part of @code{if} is
an example of an implicit @code{progn}.  @xref{Sequencing}.) 

If @var{condition} has the value @code{nil}, and no @var{else-forms} are
given, @code{if} returns @code{nil}.

@code{if} is a special form because the branch which is not selected is not
evaluated at all.  It is completely ignored.  Thus, in the example below,
@code{true} is not printed because @code{print} is never called.

@example
(if nil 
    (print 'true) 
  'very-false)
     @result{} very-false
@end example
@end defspec

@defspec cond clause@dots{}
@code{cond} chooses among an arbitrary number of alternatives.  Each
@var{clause} in the @code{cond} must be a list.  The @sc{car} of this
list is the @var{condition}; the remaining elements, if any, the
@var{body-forms}.  Thus, a clause looks like this:

@example
(@var{condition} @var{body-form}@dots{})
@end example

@code{cond} tries the clauses in textual order, by evaluating the
@var{condition} of each clause.  If the value of @var{condition} is
non-@code{nil}, the @var{body-forms} are evaluated, and the value of
the last @var{body-form} becomes the value of the @code{cond}.  The
remaining clauses are ignored.

If the value of @var{condition} is @code{nil}, the clause ``fails'', so
the following clause is tried.

If no @var{condition} evaluates to non-@code{nil}, so that every clause
fails, @code{cond} returns @code{nil}.

In the following example, if the value of @code{x} is a number, then it is
returned, but if @code{x} is not a number, then Emacs tests whether it
is a string; and if is not a string, Emacs tests whether it is a symbol.

@example
(cond ((numberp x) x)
       ((stringp x) x)
       ((symbolp x) (symbol-value x)))
@end example

A clause may also look like this:

@example
(@var{condition})
@end example

@noindent
Then, if @var{condition} is non-@code{nil} when tested, the value of
@var{condition} becomes the value of the @code{cond} form.

Often we want the last clause to be executed whenever none of the
previous clauses was successful.  To do this, we use @code{t} as the
@var{condition} of the clause, like this: @code{(t @var{body-forms})}.
The form @code{t} evaluates to @code{t}, and that is never @code{nil}, so
this clause never fails, provided the @code{cond} gets to it at all.

For example, 

@example
(cond ((eq a 1) 'foo)
      (t "default"))
     @result{} "default"
@end example

@noindent
This expression is a @code{cond} which returns @code{foo} if the value
of @code{a} is 1, and returns the string @code{"default"} otherwise.
@end defspec

Both @code{cond} and @code{if} can be written in terms of the other.
Therefore, the choice between them is a matter taste and style.  For
example:

@example
(if @var{a b c})
@equiv{}
(cond ((@var{a b}) (t @var{c}))
@end example

@node Combining Conditions, Iteration, Conditionals, Control Structures
@section Constructs for Combining Conditions

  This section describes three constructs that are often used in
combination with  @code{if} and @code{cond} to combine conditional expressions.

In themselves, @code{and} and @code{or} are a kind of multiple
conditional construct.

@defun not condition
This function tests for the falsehood of @var{condition}.  It returns
@code{t} if @var{condition} is @code{nil}, and @code{nil} otherwise.
The function @code{not} is identical to @code{null}, but we recommend
using @code{null} if you are testing for an empty list.
@end defun

@defspec and conditions@dots{}
The @code{and} special form tests whether all the @var{conditions} are
true.  It works by evaluating the @var{conditions} one by one.  If any
of the @var{conditions} evaluates to @code{nil}, then the result of the
@code{and} is already determined to be @code{nil}; so the remaining
@var{condidtions} are ignored and the @code{and} returns right away.  If
all the @var{conditions} turn out non-@code{nil}, then the value of the
last of them becomes the value of the @code{and}.

Here is an example.  The first condition returns the integer 1, which is
not @code{nil}; similarly, the second condition returns the integer 2,
which is not @code{nil}.  The third condition is @code{nil}, so the
remaining condition is never evaluated.

@example
(and (print 1) (print 2) nil (print 3))
     @print{} 1
     @print{} 2
     @result{} nil
@end example

Here is a more realistic example of using @code{and}:

@example
(if (and (consp foo) (eq (car foo) 'x))
    (message "foo is a list starting with x"))
@end example

@noindent
Note that @code{(car foo)} is not executed if @code{(consp foo)} returns
@code{nil}, thus avoiding an error.

@code{and} can be expressed in terms of either @code{if} or @code{cond}.
For example:

@example
(and @var{arg1} @var{arg2} @var{arg3})
@equiv{}
(if @var{arg1} (if @var{arg2} @var{arg3}))
@equiv{}
(cond (@var{arg1} (cond (@var{arg2} @var{arg3}))))
@end example
@end defspec

@defspec or condition@dots{}
The @code{or} special form tests whether at least one @var{condition} is
true.  It works by evaluating each @var{condition} one by one.  If any
@var{condition} evaluates to a non-@code{nil} value; then the result of
the @code{or} is already determined to be non-@code{nil}; so every
remaining @var{condition} is ignored and the @code{or} returns right
away.  The value it returns is the value of the @var{condition} just
evaluated.

If every @var{condition} turns out @code{nil}, then the @code{or}
expression returns @code{nil}.

For example, this expression tests whether @code{x} is either 0 or
@code{nil}.

@example
(or (eq x nil) (= x 0))
@end example

Like the @code{and} function, @code{or} can be written in terms of
@code{cond}.  For example:

@example
(or @var{arg1} @var{arg2} @var{arg3})
@equiv{}
(cond (@var{arg1})
      (@var{arg2})
      (@var{arg3}))
@end example

You could almost write @code{or} in terms of @code{if}, but not quite:

@example
(if @var{arg1} @var{arg1}
  (if @var{arg2} @var{arg2} 
    @var{arg3}))
@end example

@noindent
This is not correct because Emacs can evaluate @var{arg1} or @var{arg2}
twice, and @code{(or @var{arg1}} @var{arg2} @var{arg3}) never does so
more than once.
@end defspec

@node Iteration, Nonlocal Exits, Combining Conditions, Control Structures
@section Iteration

@cindex iteration
@cindex recursion
  Iteration means executing part of a program repetitively.  For example,
you might want to repeat some expressions once for each element of a list,
or once for each integer from 0 to @var{n}.  You can do this in Emacs Lisp
with the special form @code{while}:

@defspec while condition forms@dots{}
@code{while} first evaluates @var{condition}.  If the result is
non-@code{nil}, it evaluates @var{forms} in textual order.  Then it
re-evaluates @var{condition}, repeating this process until
@var{condition} evaluates to @code{nil}.

There is no limit on the number of iterations that may occur.  The loop
will continue until either @var{condition} evaluates to @code{nil} or
until an error or @code{throw} jumps out of it (@pxref{Nonlocal Exits}).

The value of a @code{while} form is always @code{nil}.

@example
(setq num 0)
     @result{} 0
(while (< num 4)
  (princ (format "Iteration %d." num))
  (setq num (1+ num)))
@print{} Iteration 0.
@print{} Iteration 1.
@print{} Iteration 2.
@print{} Iteration 3.
     @result{} nil
@end example
@end defspec

@node Nonlocal Exits, Beeping, Iteration, Control Structures
@section Nonlocal Exits
@cindex nonlocal exits

  A nonlocal exit is a transfer of control from one point in a program
to another remote point.  Nonlocal exits can occur in Emacs Lisp as
a result of errors; you can also use them under explicit control.

@menu
* Catch and Throw::	
* Examples of Catch::	
* Errors::	
* Cleanups::	
@end menu

@node Catch and Throw, Examples of Catch, Nonlocal Exits, Nonlocal Exits
@subsection Explicit Nonlocal Exits: @code{catch} and @code{throw}

  Most control constructs affect only the flow of control within the
construct itself.  The function @code{throw} is the sole exception: it
performs a nonlocal exit on command.  @code{throw} is used inside a
@code{catch}, and jumps back to that @code{catch}.  For example:

@example
(catch 'foo
  (progn
    @dots{}
           (throw 'foo t)
    @dots{}))
@end example

@noindent
The @code{throw} transfers control straight back to the corresponding
@code{catch}, which returns immediately.  The code following the
@code{throw} is not executed.  The second argument of @code{throw} is used
as the return value of the @code{catch}.

  The @code{throw} and the @code{catch} are matched through the first
argument: @code{throw} searches for a @code{catch} whose first argument is
@code{eq} to the one specified.  Thus, in the above example, the
@code{throw} specifies @code{foo}, and the @code{catch} specifies the same
symbol, so that @code{catch} does apply.  If there is more than one
@code{catch} that matches, the innermost one wins.

  All Lisp constructs between the @code{catch} and the @code{throw},
including function calls, are exited automatically along with the
@code{catch}.  When binding constructs such as @code{let} or function
calls are exited in this way, the bindings are unbound, just as they are
when the binding construct is exited normally (@pxref{Local Variables}).
Likewise, the buffer and position saved by @code{save-excursion} are
restored, and so are the buffer restrictions saved by
@code{save-restriction} and the window selection saved by
@code{save-window-excursion}.  Any cleanups established with the
@code{unwind-protect} special form are executed if the
@code{unwind-protect} is exited with a @code{throw}.

  The @code{throw} need not appear lexically within the @code{catch}
that it jumps to.  It can equally well be called from another function
called within the @code{catch}.  As long as the @code{throw} takes place
chronologically after entry to the @code{catch}, and chronologically
before exit from it, it has access to that @code{catch}.  This is why
@code{throw} can be used in commands such as @code{exit-recursive-edit}
which throw back to the Emacs command loop (@pxref{Recursive Editing}).

@quotation
@cindex Common Lisp exiting
@b{Common Lisp Note:} Most other versions of Lisp, including Common Lisp,
have several ways of transferring control nonsequentially: @code{return},
@code{return-from}, and @code{go}, for example.  Emacs Lisp has only
@code{throw}.
@end quotation

@defspec catch tag body@dots{}
@cindex tag on runtime stack
@code{catch} establishes a return point for the @code{throw} function.  The
return point is distinguished from other such return points by @var{tag},
which may be any Lisp object.  The argument @var{tag} is evaluated normally
before the return point is established.

With the return point in effect, the forms of the @var{body} are evaluated
in textual order.  If the forms execute normally, without error or nonlocal
exit, the value of the last body form is returned from the @code{catch}.

If, instead, a @code{throw} is done specifying the same value @var{tag},
the @code{catch} exits immediately; the value it returns is whatever was
specified as the second argument of @code{throw}.
@end defspec

@defun throw tag value
The purpose of @code{throw} is to return from a return point previously
established with @code{catch}.  The argument @var{tag} is used to choose
among the various existing return points; it must be @code{eq} to the value
specified in the @code{catch}.  If multiple return points match @var{tag},
the innermost one is used.

The argument @var{value} is used as the value to return from that
@code{catch}.

@kindex no-catch
If no return point is in effect with tag @var{tag}, then a @code{no-catch}
error is signaled with data @code{(@var{tag} @var{value})}.
@end defun

@node Examples of Catch, Errors, Catch and Throw, Nonlocal Exits
@subsection Examples of @code{catch} and @code{throw}

  One way to use @code{catch} and @code{throw} is to exit from a doubly
nested loop.  (In most languages, this would be done with a ``go to''.)
Here we compute @code{(foo @var{i} @var{j})} for @var{i} and @var{j}
varying from 0 to 9:

@example
(defun search-foo ()
  (catch 'loop
    (let ((i 0))
      (while (< i 10)
        (let ((j 0))
          (while (< j 10)
            (if (foo i j)
                (throw 'loop (list i j)))
            (setq j (1+ j))))
        (setq i (1+ i))))))
@end example

@noindent
If @code{foo} ever returns non-@code{nil}, we stop immediately and return a
list of @var{i} and @var{j}.  If @code{foo} always returns @code{nil}, the
@code{catch} returns normally, and the value is @code{nil}, since that
is the result of the @code{while}.

  Here are two tricky examples, slighly different, showing two
return points at once.  First, two return points with the same tag,
@code{hack}:

@example
(defun catch2 (tag)
  (catch tag
    (throw 'hack 'yes)))
@result{} catch2

(catch 'hack 
  (print (catch2 'hack))
  'no)
@print{} yes
@result{} no
@end example

@noindent
Since both return points have tags that match the @code{throw}, it goes to
the inner one, the one established in @code{catch2}.  Therefore,
@code{catch2} returns normally with value @code{yes}, and this value is
printed.  Finally the second body form in the outer @code{catch}, which is
@code{'no}, is evaluated and returned from the outer @code{catch}.

  Now let's change the argument given to @code{catch2}:

@example
(defun catch2 (tag)
  (catch tag
    (throw 'hack 'yes)))
@result{} catch2

(catch 'hack
  (print (catch2 'quux))
  'no)
@result{} yes
@end example

@noindent
We still have two return points, but this time only the outer one has the
tag @code{hack}; the inner one has the tag @code{quux} instead.  Therefore,
the @code{throw} returns the value @code{yes} from the outer return point.
The function @code{print} is never called, and the body-form @code{'no} is
never evaluated.

@node Errors, Cleanups, Examples of Catch, Nonlocal Exits
@subsection Errors
@cindex errors

  When Emacs Lisp attempts to evaluate a form that, for some reason,
cannot be evaluated, it @dfn{signals} an @dfn{error}.

  When an error occurs, Emacs's default reaction is to print an error
message and terminate execution of the current command.  This is the
right thing in most cases, such as if you type @kbd{C-f} at the end of
the buffer.

  In complicated programs, simple termination may not be what you want.
For example, the program may have made temporary changes in data
structures, or created temporary buffers which must, at all costs, be
deleted before the program is finished.  In such cases, you would use
@code{unwind-protect} to establish @dfn{cleanup expressions} to be
evaluated in case of error.  Occasionally, you may wish the program to
continue execution despite an error in a subroutine.  In these cases,
you would use @code{condition-case} to establish @dfn{error handlers} to
recover control in case of error.

  Each error has an associated @dfn{error symbol} or @dfn{error name}
which identifies the event that caused the problem.  The error symbol is
useful for programs that  handle some kinds of error, but not all.

@menu
* Signalling Errors::
* Processing of Errors::
* Handling Errors::
* Error Names::
@end menu

@node Signalling Errors, Processing of Errors, Errors, Errors
@subsubsection How to Signal an Error

  Most errors are signaled ``automatically'' within Lisp primitives
which you call for other purposes, such as if you try to take the @sc{car} of
an integer or move forward a character at the end of the buffer; but you
can signal them explicitly with the functions @code{error} and
@code{signal}.

@defun error format-string &rest args
This function signals an error with an error message constructed by
applying @code{format} (@pxref{Conversion of Characters and Strings}) to
@var{format-string} and @var{args}.

Typical uses of @code{error} is shown in the following examples:

@example
(error "You have committed an error.  Try doing something different.")
     @error{} You have committed an error.  Try doing something different.

(error "You have committed %d errors.  You don't learn fast." 10)
     @error{} You have committed 10 errors.  You don't learn fast.
@end example

@code{error} works by calling @code{signal} with the error symbol
@code{error} and the string returned by @code{format} as the only
arguments.
@end defun

@defun signal error-symbol data
This function signals an error named by @var{error-symbol}.  The
argument @var{data} is a list of additional Lisp objects relevant to the
circumstances of the error.

@cindex error-conditions property
@cindex peculiar error
@var{error-symbol} must have an @code{error-conditions} property whose
value is a list of condition names.  @xref{Error Names}, for a
description of how to set up your own error conditions.

The number and significance of the objects in @var{data} depends on
@var{error-symbol}.  For example, in an @code{wrong-type-arg} error,
there are two objects in the list: a predicate which describes the type
that was expected, and the object which failed to fit that type.

Both @var{error-symbol} and @var{data} are available to any error
handlers which handle the error: a list @w{@code{(@var{error-symbol} .@:
@var{data})}} is constructed to become the value of the local variable
bound in the @code{condition-case} form.  If the error is not handled,
both of them are used in printing the error message.

@example
(signal 'wrong-number-of-arguments '(x y))
     @error{} Wrong number of arguments: x, y

(signal 'no-such-error '("My unknown error condition."))
     @error{} peculiar error: "My unknown error condition."
@end example
@end defun

@quotation
@cindex Common Lisp errors
@b{Common Lisp Note:} The function @code{signal} is the sole function
that can signal an error (the @code{error} function calls it).  This
implies that Emacs Lisp has nothing like the Common Lisp concept of
continuable errors.
@end quotation

@node Processing of Errors, Handling Errors, Signalling Errors, Errors
@subsubsection How Emacs Processes Errors

When an error is signaled, Emacs searches for an active @dfn{handler}
for the error.  A handler is a specially marked place in the Lisp code
of the current function or any of the functions by which it was called.
If an applicable handler exists, its code is executed, and control
resumes following the handler.  The handler executes in the environment
of the @code{condition-case} which established it; all functions called
within that @code{condition-case} have already been exited, and the
handler cannot return to them.

If no applicable handler is in effect in your program, the current
command is terminated and control returns to the editing command loop,
because the command loop has its own handler for all kinds of errors.
The command loop's handler uses the error symbol and associated data to
print an error message.

@cindex debugger
@vindex debug-on-error use
If no handler applies, the Lisp debugger may be called.  The debugger is
enabled if the variable @code{debug-on-error} (@pxref{Debug Functions})
is non-@code{nil}.  Unlike error handlers, the debugger runs in the
environment of the error, so that you can examine values of variables
precisely as they were at the time of the error.  @xref{Debugging}, for
the details.

@node Handling Errors, Error Names, Processing of Errors, Errors
@subsubsection Handling Errors

The usual effect of signaling an error is to terminate the command that
is running and return immediately to the Emacs editing command loop.
You can arrange to trap errors occuring in a part of your program by
establishing an @dfn{error handler} with the special form
@code{condition-case}.  A simple example looks like this:

@example
(condition-case nil
    (delete-file filename)
  (error nil))
@end example

@noindent
This deletes the file, catching any error that occurs and returning
@code{nil}.

The second argument of @code{condition-case} is called the
@dfn{protected form}.  (In the example above, that is a call to
@code{delete-file}.)  The error handlers go into effect when this form
begins execution and are deactivated when this form returns.  They
remain in effect for all the intervening time.  In particular, they are
in effect during the execution of subroutines called by this form, and
their subroutines, and so on.  This is a good thing, since, strictly
speaking, errors can be signaled only by Lisp primitives, not by the
protected form itself.

The arguments after the second one are handlers.  Each handler lists one
or more @dfn{condition names} (which are symbols) to specify which
errors it will handle.  The error symbol specified when an error is
signaled also defines a list of condition names.  A handler applies to
an error if they have any condition names in common.  In the example
above, there is one handler, and it specifies one condition name,
@code{error}.  That condition includes all errors.

The search for an applicable handler checks all the established handlers
starting with the most recently established one.  Thus, if two nested
@code{condition-case} forms try to handle the same error, the inner of
the two will actually handle it.

When an error is handled, control returns to the handler, executing the
cleanups of all @code{unwind-protect} forms that are exited by doing so.
Then, the body of the handler is executed.  After this, execution
continues by returning from the @code{condition-case} form.  Because the
protected form is exited completely before execution of the handler, the
handler cannot resume execution at the point of the error, nor can it
examine variable bindings that were made within the protected form.  All
it can do is clean up and proceed.

Error signaling and handling have some resemblance to @code{throw} and
@code{catch}, but they are entirely separate facilities.  An error
cannot be caught by a @code{catch}, and a @code{throw} cannot be handled
by an error handler (though if there is no @code{catch}, @code{throw}
will signal an error which can be handled).

@defspec condition-case var protected-form handlers@dots{}
@cindex runtime stack
This special form establishes the error handlers @var{handlers} around
the execution of @var{protected-form}.  If @var{protected-form} executes
without error, the value it returns becomes the value of the
@code{condition-case} form; in this case, the @code{condition-case} has
no effect.  The @code{condition-case} form makes a difference when an
error occurs during @var{protected-form}.

Each of the @var{handlers} is a list of the form @code{(@var{conditions}
@var{body}@dots{})}.  @var{conditions} is a condition name to be
handled, or a list of condition names; @var{body} is one or more Lisp
expressions to be executed when this handler handles an error.

Each error that occurs has an @dfn{error symbol} which describes what
kind of error it is.  The @code{error-conditions} property of this
symbol is a list of condition names (@pxref{Error Names}).  Emacs
searches all the active @code{condition-case} forms for a handler which
specifies one or more of these names; the innermost matching
@code{condition-case} handles the error.  The handlers in this
@code{condition-case} are tested in the order in which they appear.

The body of the handler is then executed, and the @code{condition-case}
returns normally, using the value of the last form in the body as the
overall value.

The argument @var{var} is a variable.  @code{condition-case} does not
bind this variable when executing the @var{protected-form}, only when it
handles an error.  At that time, @var{var} is bound locally to a list of
the form @code{(@var{error-symbol} . @var{data})}, giving the
particulars of the error.  The handler can refer to this list to decide
what to do.  For example, if the error is for failure opening a file,
the file name is the second element of @var{data}---the third element of
@var{var}.
@end defspec

@cindex arith-error example
  Here is an example of using @code{condition-case} to handle the error
that results from dividing by zero.  The handler prints out a warning
message and returns a very large number.

@example
(defun safe-divide (dividend divisor)
  (condition-case err		     
      ;; @r{Protected form.}
      (/ dividend divisor)		
    ;; @r{The handler.}
    (arith-error			; @r{Condition.}
     (princ (format "Arithmetic error: %s" err))
     1000000)))
     @result{} safe-divide
(safe-divide 5 0)

     @print{} Arithmetic error: (arith-error)
     @result{} 1000000
@end example

@noindent
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,

@example
(safe-divide nil 3)
     @error{} Wrong type argument: 0, nil
@end example

  Here is a @code{condition-case} that catches all kinds of errors,
including those signaled with @code{error}:

@example
(setq baz 34)
     @result{} 34

@findex condition-case @r{example}
(condition-case err
    (if (eq baz 35)
        t
      ;; @r{This is a call to the function @code{error}.}
      (error "Rats!  The variable %s was %s, not 35." 'baz baz))
  ;; @r{This is the handler; it is not a form.}
  (error (princ (format "The error was: %s" err)) 
         2))

     @print{} The error was: (error "Rats!  The variable baz was 34, not 35.")
     @result{} 2
@end example

  @code{condition-case} may be used to trap errors that are unexpected,
such as in a function that executes an expression read from the user.
It may also be used to trap errors that are expected, such as failure to
open a file when you call @code{insert-file-contents}.

@node Error Names,  , Handling Errors, Errors
@subsubsection Error Symbols and Condition Names
@cindex condition names
@cindex user-defined errors
@kindex error-conditions

  When you signal an error, you specify an @dfn{error symbol} to specify
the kind of error you have in mind.  Each error has one and only one
error symbol to categorize it.  This is the finest classification of
errors defined by the Lisp language.

  These narrow classifications are grouped into a hierarchy of wider
classes called @dfn{error conditions}, identified by @dfn{condition
names}.  The narrowest such classes belong to the error symbols
themselves: each error symbol is also a condition name.  There are also
condition names for more extensive classes, up to the condition name
@code{error} which takes in all kinds of errors.  Thus, each error has
one or more condition names: @code{error}, the error symbol if that
is distinct from @code{error}, and perhaps some intermediate
classifications.

  In order for a symbol to be usable as an error symbol, it must have an
@code{error-conditions} property which gives a list of condition names.
This list defines the conditions which this kind of error belongs to.
(The error symbol itself, and the symbol @code{error}, should always be
members of this list.)  Thus, the hierarchy of condition names is
defined by the @code{error-conditions} properties of the error symbols.

  In addition to the @code{error-conditions} list, the error symbol should
have an @code{error-message} property whose value is a string to be
printed when that error is signaled but not handled.  If the
@code{error-message} property exists, but is not a string, the
untrappable @samp{peculiar error} will be signaled.
@cindex peculiar error

  Here is how we define a new error symbol, @code{new-error}, and how we
would then signal it:

@example
(put 'new-error 'error-conditions '(error my-own-errors new-error))
     @result{} (error my-own-errors new-error)
(put 'new-error 'error-message "A new error")
     @result{} "A new error"
@end example

@noindent
This error has three condition names: @code{new-error}, the narrowest
classification; @code{my-own-errors}, which we imagine is a wider
classification; and @code{error}, which is the widest of all.
 
  Naturally, Emacs will never signal a @code{new-error} on its own; only
an explicit call to @code{signal} (@pxref{Errors}) in your code can do
this:

@example
(signal 'new-error '(x y))
     @error{} A new error: x, y
@end example

  This error can be handled through any of the three condition names.
This example handles @code{new-error} and any other errors in the class
@code{my-own-errors}:

@example
(condition-case foo
    (bar nil t)
  (my-own-errors nil))
@end example

  The significant way that errors are classified is by their condition
names.  They are the names used to match errors with handlers.  An error
symbol serves only as a convenient way to specify the intended error
message and list of condition names.  Lisp could have been designed
differently, so that @code{signal} would need a list of condition names
rather than one error symbol, but that would have made it more
cumbersome.

  By contrast, using only error symbols without condition names would
seriously decrease the power of @code{condition-case}.  Condition names
make it possible to categorize errors at various levels of generality
when you write an error handler.  Using error symbols alone would
eliminate all but the narrowest level of classification.

  In the appendix (@pxref{Standard Errors}) is a list of all the standard
error symbols and their conditions.

@node Cleanups,  , Errors, Nonlocal Exits
@subsection Cleaning up from Nonlocal Exits

  The @code{unwind-protect} construct is essential whenever you temporarily
put a data structure in an inconsistent state; it permits you to make sure
to make the data consistent in the event of an error.

@defspec unwind-protect body cleanup-forms@dots{}
@cindex cleanup forms
@cindex protected forms
@cindex error cleanup
@code{unwind-protect} executes the @var{body} with a guarantee that
the @var{cleanup-forms} will be evaluated if control leaves
@var{body}, no matter how that happens.  The @var{body} may complete
normally, or execute a @code{throw} over the @code{unwind-protect}, or
cause an error; in all cases, the @var{cleanup-forms} will be
evaluated.

Only the @var{body} is actually protected by the
@code{unwind-protect}.  If any of the @var{cleanup-forms} themselves
exit (e.g., via a @code{throw} or an error), it is @emph{not}
guaranteed that the rest of them will be executed.  If the failure of
one of the @var{cleanup-forms} has the potential to cause trouble,
then it should be protected by another @code{unwind-protect} around
that form.

The number of currently active @code{unwind-protect} forms counts,
together with the number of local variable bindings, against the limit
@code{max-specpdl-size} (@pxref{Local Variables}).
@end defspec

  For example, you might make an invisible buffer for temporary use, which
you wish to be sure to kill before the next command:

@example
(save-excursion
  (let ((buffer (get-buffer-create " *temp*")))
    (set-buffer buffer)
    (unwind-protect
        @var{body}
      (kill-buffer buffer))))
@end example

@noindent
You might think that we could just as well write @code{(kill-buffer
(current-buffer))} and dispense with the variable @code{buffer}.
However, the way shown above safer, if @var{body} happens to get an
error after switching to a different buffer!  (Alternatively, you could
write another @code{save-excursion} around the body, to ensure that the
temporary buffer becomes current in time to kill it.)

@findex ftp-login
  Here is an actual example taken from the file @file{ftp.el}.  It creates
a process (@pxref{Processes}) to try to establish a connection to a remote
machine.  As the function @code{ftp-login} is highly susceptible to
numerous problems which the writer of the function cannot anticipate, it is
protected with a form that guarantees deletion of the process in the event
of failure.  Otherwise, Emacs might fill up with useless subprocesses.

@example
(let ((win nil))
  (unwind-protect
      (progn
        (setq process (ftp-setup-buffer host file))
        (if (setq win (ftp-login process host user password))
            (message "Logged in")
          (error "Ftp login failed")))
    (or win (and process (delete-process process)))))
@end example

  This example actually has a small bug: if the user types @kbd{C-g} to
quit, and the quit happens immediately after the function
@code{ftp-setup-buffer} returns but before the variable @code{process} is
set, the process will not be killed.  There is no easy way to fix this bug,
but at least it is very unlikely.

@node Beeping,  , Nonlocal Exits, Control Structures
@section Beeping

@cindex beeping
@cindex dinging
@cindex bell

  You can make Emacs ring a bell, beep, or perhaps, blink the screen.
This attracts attention.  If too frequent, the action is irritating.  Be
careful not to use beeping when an error message is appropriate.
(@xref{Errors}.)

@defun ding &optional dont-terminate
@cindex keyboard macro termination
  This function beeps, or flashes the screen (see @code{visible-bell} below).
It also terminates any keyboard macro currently executing unless
@var{dont-terminate} is non-@code{nil}.
@end defun

@defun beep &optional dont-terminate
This is a synonym for @code{ding}.
@end defun

@defvar visible-bell
  This global variable determines whether Emacs will try to flash the
screen to represent a bell.  @code{t} means do, @code{nil} means don't.
This is only effective if the termcap entry for the terminal in use has
the visible bell flag (@b{vb}) set.
@end defvar