Skip to main content

11.7.3 Errors

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

When an error is signaled, Emacs’s default reaction is to print an error message and terminate execution of the current command. This is the right thing to do in most cases, such as if you type 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 that should be deleted before the program is finished. In such cases, you would use unwind-protect to establish cleanup expressions to be evaluated in case of error. (See Cleanups.) Occasionally, you may wish the program to continue execution despite an error in a subroutine. In these cases, you would use condition-case to establish error handlers to recover control in case of error.

Resist the temptation to use error handling to transfer control from one part of the program to another; use catch and throw instead. See Catch and Throw.

Signaling Errors  How to report an error.
Processing of Errors  What Emacs does when you report an error.
Handling Errors  How you can trap errors and continue execution.
Error Symbols  How errors are classified for trapping them. How to Signal an Error

Signaling an error means beginning error processing. Error processing normally aborts all or part of the running program and returns to a point that is set up to handle the error (see Processing of Errors). Here we describe 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 CAR of an integer or move forward a character at the end of the buffer. You can also signal errors explicitly with the functions error and signal.

Quitting, which happens when the user types C-g, is not considered an error, but it is handled almost like an error. See Quitting.

Every error specifies an error message, one way or another. The message should state what is wrong (“File does not exist"), not how things ought to be (“File must exist"). The convention in Emacs Lisp is that error messages should start with a capital letter, but should not end with any sort of punctuation.

function error format-string \&rest args

This function signals an error with an error message constructed by applying format-message (see Formatting Strings) to format-string and args.

These examples show typical uses of error:

(error "That is an error -- try something else")
error→ That is an error -- try something else
(error "Invalid name `%s'" "A%%B")
error→ Invalid name ‘A%%B’

error works by calling signal with two arguments: the error symbol error, and a list containing the string returned by format-message.

Typically grave accent and apostrophe in the format translate to matching curved quotes, e.g., "Missing `%s'" might result in "Missing ‘foo’". See Text Quoting Style, for how to influence or inhibit this translation.

Warning: If you want to use your own string as an error message verbatim, don’t just write (error string). If string string contains ‘%’, ‘`’, or ‘'’ it may be reformatted, with undesirable results. Instead, use (error "%s" string).

function signal error-symbol data

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

The argument error-symbol must be an error symbol—a symbol defined with define-error. This is how Emacs Lisp classifies different sorts of errors. See Error Symbols, for a description of error symbols, error conditions and condition names.

If the error is not handled, the two arguments are used in printing the error message. Normally, this error message is provided by the error-message property of error-symbol. If data is non-nil, this is followed by a colon and a comma separated list of the unevaluated elements of data. For error, the error message is the CAR of data (that must be a string). Subcategories of file-error are handled specially.

The number and significance of the objects in data depends on error-symbol. For example, with a wrong-type-argument error, there should be two objects in the list: a predicate that describes the type that was expected, and the object that failed to fit that type.

Both error-symbol and data are available to any error handlers that handle the error: condition-case binds a local variable to a list of the form (error-symbol . data) (see Handling Errors).

The function signal never returns.

(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"

function user-error format-string \&rest args

This function behaves exactly like error, except that it uses the error symbol user-error rather than error. As the name suggests, this is intended to report errors on the part of the user, rather than errors in the code itself. For example, if you try to use the command Info-history-back (l) to move back beyond the start of your Info browsing history, Emacs signals a user-error. Such errors do not cause entry to the debugger, even when debug-on-error is non-nil. See Error Debugging.

Common Lisp note: Emacs Lisp has nothing like the Common Lisp concept of continuable errors. How Emacs Processes Errors

When an error is signaled, signal searches for an active handler for the error. A handler is a sequence of Lisp expressions designated to be executed if an error happens in part of the Lisp program. If the error has an applicable handler, the handler is executed, and control resumes following the handler. The handler executes in the environment of the condition-case that established it; all functions called within that condition-case have already been exited, and the handler cannot return to them.

If there is no applicable handler for the error, it terminates the current command and returns control to the editor command loop. (The command loop has an implicit handler for all kinds of errors.) The command loop’s handler uses the error symbol and associated data to print an error message. You can use the variable command-error-function to control how this is done:

variable command-error-function

This variable, if non-nil, specifies a function to use to handle errors that return control to the Emacs command loop. The function should take three arguments: data, a list of the same form that condition-case would bind to its variable; context, a string describing the situation in which the error occurred, or (more often) nil; and caller, the Lisp function which called the primitive that signaled the error.

An error that has no explicit handler may call the Lisp debugger. The debugger is enabled if the variable debug-on-error (see Error Debugging) is non-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. Writing Code to Handle Errors

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

(condition-case nil
(delete-file filename)
(error nil))

This deletes the file named filename, catching any error and returning nil if an error occurs. (You can use the macro ignore-errors for a simple case like this; see below.)

The condition-case construct is often used to trap errors that are predictable, such as failure to open a file in a call to insert-file-contents. It is also used to trap errors that are totally unpredictable, such as when the program evaluates an expression read from the user.

The second argument of condition-case is called the protected form. (In the example above, the protected form is a call to 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 functions called by this form, in their subroutines, and so on. This is a good thing, since, strictly speaking, errors can be signaled only by Lisp primitives (including signal and error) called by the protected form, not by the protected form itself.

The arguments after the protected form are handlers. Each handler lists one or more 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, error, which covers all errors.

The search for an applicable handler checks all the established handlers starting with the most recently established one. Thus, if two nested condition-case forms offer to handle the same error, the inner of the two gets to handle it.

If an error is handled by some condition-case form, this ordinarily prevents the debugger from being run, even if debug-on-error says this error should invoke the debugger.

If you want to be able to debug errors that are caught by a condition-case, set the variable debug-on-signal to a non-nil value. You can also specify that a particular handler should let the debugger run first, by writing debug among the conditions, like this:

(condition-case nil
(delete-file filename)
((debug error) nil))

The effect of debug here is only to prevent condition-case from suppressing the call to the debugger. Any given error will invoke the debugger only if debug-on-error and the other usual filtering mechanisms say it should. See Error Debugging.

macro condition-case-unless-debug var protected-form handlers…

The macro condition-case-unless-debug provides another way to handle debugging of such forms. It behaves exactly like condition-case, unless the variable debug-on-error is non-nil, in which case it does not handle any errors at all.

Once Emacs decides that a certain handler handles the error, it returns control to that handler. To do so, Emacs unbinds all variable bindings made by binding constructs that are being exited, and executes the cleanups of all unwind-protect forms that are being exited. Once control arrives at the handler, the body of the handler executes normally.

After execution of the handler body, execution returns from the 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 throw and catch (see Catch and Throw), but they are entirely separate facilities. An error cannot be caught by a catch, and a throw cannot be handled by an error handler (though using throw when there is no suitable catch signals an error that can be handled).

special form condition-case var protected-form handlers…

This special form establishes the error handlers handlers around the execution of protected-form. If protected-form executes without error, the value it returns becomes the value of the condition-case form; in this case, the condition-case has no effect. The condition-case form makes a difference when an error occurs during protected-form.

Each of the handlers is a list of the form (conditions body…). Here conditions is an error condition name to be handled, or a list of condition names (which can include debug to allow the debugger to run before the handler). A condition name of t matches any condition. body is one or more Lisp expressions to be executed when this handler handles an error. Here are examples of handlers:

(error nil)

(arith-error (message "Division by zero"))

((arith-error file-error)
"Either division by zero or failure to open a file"))

Each error that occurs has an error symbol that describes what kind of error it is, and which describes also a list of condition names (see Error Symbols). Emacs searches all the active condition-case forms for a handler that specifies one or more of these condition names; the innermost matching condition-case handles the error. Within this condition-case, the first applicable handler handles the error.

After executing the body of the handler, the condition-case returns normally, using the value of the last form in the handler body as the overall value.

The argument var is a variable. condition-case does not bind this variable when executing the protected-form, only when it handles an error. At that time, it binds var locally to an error description, which is a list giving the particulars of the error. The error description has the form (error-symbol . data). 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 data—the third element of the error description.

If var is nil, that means no variable is bound. Then the error symbol and associated data are not available to the handler.

Sometimes it is necessary to re-throw a signal caught by condition-case, for some outer-level handler to catch. Here’s how to do that:

  (signal (car err) (cdr err))

where err is the error description variable, the first argument to condition-case whose error condition you want to re-throw. See Definition of signal.

function error-message-string error-descriptor

This function returns the error message string for a given error descriptor. It is useful if you want to handle an error by printing the usual error message for that error. See Definition of signal.

Here is an example of using condition-case to handle the error that results from dividing by zero. The handler displays the error message (but without a beep), then returns a very large number.

(defun safe-divide (dividend divisor)
(condition-case err
;; Protected form.
(/ dividend divisor)
    ;; The handler.
(arith-error ; Condition.
;; Display the usual message for this error.
(message "%s" (error-message-string err))
⇒ safe-divide
(safe-divide 5 0)
-| Arithmetic error: (arith-error)
⇒ 1000000

The handler specifies condition name arith-error so that it will handle only division-by-zero errors. Other kinds of errors will not be handled (by this condition-case). Thus:

(safe-divide nil 3)
error→ Wrong type argument: number-or-marker-p, nil

Here is a condition-case that catches all kinds of errors, including those from error:

(setq baz 34)
⇒ 34
(condition-case err
(if (eq baz 35)
;; This is a call to the function error.
(error "Rats! The variable %s was %s, not 35" 'baz baz))
;; This is the handler; it is not a form.
(error (princ (format "The error was: %s" err))
-| The error was: (error "Rats! The variable baz was 34, not 35")
⇒ 2

macro ignore-errors body…

This construct executes body, ignoring any errors that occur during its execution. If the execution is without error, ignore-errors returns the value of the last form in body; otherwise, it returns nil.

Here’s the example at the beginning of this subsection rewritten using ignore-errors:

(delete-file filename))

macro ignore-error condition body…

This macro is like ignore-errors, but will only ignore the specific error condition specified.

  (ignore-error end-of-file
(read ""))

condition can also be a list of error conditions.

macro with-demoted-errors format body…

This macro is like a milder version of ignore-errors. Rather than suppressing errors altogether, it converts them into messages. It uses the string format to format the message. format should contain a single ‘%’-sequence; e.g., "Error: %S". Use with-demoted-errors around code that is not expected to signal errors, but should be robust if one does occur. Note that this macro uses condition-case-unless-debug rather than condition-case. Error Symbols and Condition Names

When you signal an error, you specify an 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 Emacs Lisp language.

These narrow classifications are grouped into a hierarchy of wider classes called error conditions, identified by 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 error which takes in all kinds of errors (but not quit). Thus, each error has one or more condition names: error, the error symbol if that is distinct from error, and perhaps some intermediate classifications.

function define-error name message \&optional parent

In order for a symbol to be an error symbol, it must be defined with define-error which takes a parent condition (defaults to error). This parent defines the conditions that this kind of error belongs to. The transitive set of parents always includes the error symbol itself, and the symbol error. Because quitting is not considered an error, the set of parents of quit is just (quit).

In addition to its parents, the error symbol has a message which is a string to be printed when that error is signaled but not handled. If that message is not valid, the error message ‘peculiar error’ is used. See Definition of signal.

Internally, the set of parents is stored in the error-conditions property of the error symbol and the message is stored in the error-message property of the error symbol.

Here is how we define a new error symbol, new-error:

(define-error 'new-error "A new error" 'my-own-errors)

This error has several condition names: new-error, the narrowest classification; my-own-errors, which we imagine is a wider classification; and all the conditions of my-own-errors which should include error, which is the widest of all.

The error string should start with a capital letter but it should not end with a period. This is for consistency with the rest of Emacs.

Naturally, Emacs will never signal new-error on its own; only an explicit call to signal (see Definition of signal) in your code can do this:

(signal 'new-error '(x y))
error→ A new error: x, y

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

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

The significant way that errors are classified is by their condition names—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. It would be cumbersome to give signal a list of condition names rather than one error symbol.

By contrast, using only error symbols without condition names would seriously decrease the power of 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.

See Standard Errors, for a list of the main error symbols and their conditions.