Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 38 ยท Condition System

Conditions: Signaling and Handling Errors

Learn the Common Lisp condition system: define-condition, error, warn and signal, handler-case versus handler-bind, condition hierarchies and why handlers run before the stack unwinds.

Common Lisp's condition system is a generalization of exceptions. Where most languages split error handling into "throw" and "catch" only, Lisp separates three jobs: signaling that something happened, handling it (deciding what to do), and restarting (offering ways to continue). This lesson covers the first two; restarts are next.

No Common Lisp implementation runs on this site, so Lisp code is read-only and only outputs I am certain about are shown. The JavaScript examples are labelled stand-ins that model the handler stack.

Conditions are objects

A condition is an instance of a class descended from condition. The standard hierarchy includes serious-condition, error, warning and simple-error. Define your own with define-condition:

LISP
(define-condition insufficient-funds (error)
  ((needed    :initarg :needed    :reader needed)
   (available :initarg :available :reader available))
  (:report (lambda (c stream)
             (format stream "Need ~a but only ~a available"
                     (needed c) (available c)))))

:report controls how the condition prints, which the debugger and the ~a directive use. Conditions are CLOS classes, so you get inheritance and slots for free.

Signaling

Function Behavior if no handler takes control
(error c) invokes the debugger
(warn c) prints a warning and continues, returning NIL
(signal c) does nothing and returns NIL
LISP
(defun withdraw (account amount)
  (when (> amount (balance account))
    (error 'insufficient-funds :needed amount :available (balance account)))
  (decf (balance account) amount))

You can pass the class name and initargs (as here), a condition object, or a format string with arguments: (error "Bad value: ~a" x) creates a simple-error.

handler-case: catch and unwind

handler-case works like try/catch: if a matching condition is signaled in the body, the stack unwinds to the handler-case and the clause runs.

LISP
(handler-case (withdraw acct 500)
  (insufficient-funds (c)
    (format t "Declined: ~a~%" c)
    nil))

Clauses are tried in order and match by class, including subclasses. A (error (e) ...) clause catches any error. The last clause may be (:no-error (value) ...), which runs when the body returns normally. ignore-errors is shorthand returning (values nil condition) when an error occurs.

LISP
(handler-case (parse-integer "12x")
  (parse-error () :bad-number))
;; => :BAD-NUMBER

handler-bind: run the handler where the signal happened

handler-bind is different and more powerful. The handler is a function that runs at the point of the signal, on top of the stack that signaled, before anything unwinds. It may decline (by returning normally), in which case the next handler is tried, or take control with a non-local exit such as invoking a restart or return-from.

LISP
(handler-bind ((warning (lambda (w)
                          (format t "Noted: ~a~%" w)
                          (muffle-warning w))))
  (warn "disk almost full")
  (format t "still running~%"))

Here the handler logs and calls muffle-warning, a restart established by warn, so execution continues after the warn call. With handler-case that is impossible, because the stack has already unwound.

flowchart TD
    A["(error c) signaled deep in the code"] --> B["Search handler stack, newest first"]
    B --> C{"handler-bind: function runs here"}
    C -->|"returns normally"| B
    C -->|"non-local exit"| D["Unwind to chosen point"]
    B --> E{"handler-case matches"}
    E --> D
    B -->|"none found"| F["Debugger"]

handler-bind runs on the signaling stack; handler-case unwinds first.

JS Stand-in: a handler stack with signal and handler-bind

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Condition hierarchies guide handlers

Design a small hierarchy so callers can catch at the right granularity:

LISP
(define-condition app-error (error) ())
(define-condition config-error (app-error) ((path :initarg :path :reader path)))
(define-condition network-error (app-error) ())

A handler for app-error catches both; a handler for config-error only the file case. Avoid handling bare error (or worse serious-condition) in library code, because it hides programming errors like type errors that nobody expected.

Warnings, notes and signal

signal is how you announce events that are not necessarily errors, for example progress or a deprecation, because it returns NIL if no handler transfers control. A warning condition is conventionally signaled with warn. Conditions are not limited to errors at all: they are a general "something happened" channel between low-level code and policy higher up.

LISP
(define-condition row-skipped (condition) ((line :initarg :line :reader line)))

(defun read-rows (lines)
  (loop for l in lines
        when (blank-p l) do (signal 'row-skipped :line l)
        else collect (parse l)))

Callers who do not care ignore it; callers who do can count skipped rows with a handler-bind.

The debugger

If no handler handles an error, the debugger runs (*debugger-hook* customizes it). Interactively that shows the backtrace and the available restarts such as ABORT, CONTINUE or USE-VALUE. Scripts usually set --disable-debugger or wrap the main function in a handler-case that exits with a message.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main difference between handler-case and handler-bind?

    handler-case is try/catch (unwind then run clause). handler-bind calls your function at the signal point, so restarts can still continue the computation.
  2. 2. What does (signal c) do if no handler takes control?

    Unlike error, signal simply returns NIL when unhandled, which makes it suitable for non-error events.
  3. 3. Why avoid (handler-case ... (error () ...)) in library code?

    Catch the narrowest condition class that describes what you can actually recover from.
  4. 4. What does the :report option of define-condition do?

    The report function prints a human-readable message, used by the debugger and ~a.

Summary

  • Conditions are CLOS objects with their own hierarchy; define them with define-condition.
  • error, warn and signal announce; handler-case unwinds then handles; handler-bind handles in place.
  • Use a small condition hierarchy and catch narrowly.
  • Unhandled errors enter the debugger with restarts available.
  • The JavaScript handler stack is a stand-in model, not Lisp.

Next: Restarts: Recovering Without Unwinding