8.2.1 condition-case

As we have seen earlier (see Generate an Error Message), when the Emacs Lisp interpreter has trouble evaluating an expression, it provides you with help; in the jargon, this is called “signaling an error”. Usually, the computer stops the program and shows you a message.

However, some programs undertake complicated actions. They should not simply stop on an error. In the kill-region function, the most likely error is that you will try to kill text that is read-only and cannot be removed. So the kill-region function contains code to handle this circumstance. This code, which makes up the body of the kill-region function, is inside of a condition-case special form.

The template for condition-case looks like this:

(condition-case
  var
  bodyform
  error-handler…)

The second argument, bodyform, is straightforward. The condition-case special form causes the Lisp interpreter to evaluate the code in bodyform. If no error occurs, the special form returns the code’s value and produces the side-effects, if any.

In short, the bodyform part of a condition-case expression determines what should happen when everything works correctly.

However, if an error occurs, among its other actions, the function generating the error signal will define one or more error condition names.

An error handler is the third argument to condition-case. An error handler has two parts, a condition-name and a body. If the condition-name part of an error handler matches a condition name generated by an error, then the body part of the error handler is run.

As you will expect, the condition-name part of an error handler may be either a single condition name or a list of condition names.

Also, a complete condition-case expression may contain more than one error handler. When an error occurs, the first applicable handler is run.

Lastly, the first argument to the condition-case expression, the var argument, is sometimes bound to a variable that contains information about the error. However, if that argument is nil, as is the case in kill-region, that information is discarded.

In brief, in the kill-region function, the code condition-case works like this:

If no errors, run only this code
    but, if errors, run this other code.