Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 38 ยท Condition System

Non-Local Exits, Assertions and Cleanup

Learn Common Lisp non-local exits with block and return-from, catch and throw, guarantee cleanup with unwind-protect and check inputs with assert, check-type, ecase and etypecase.

The condition system rests on a few lower-level control tools. This lesson covers them: lexical exits (block, return-from), dynamic exits (catch, throw), guaranteed cleanup (unwind-protect) and the assertion macros that signal well-formed conditions with useful restarts.

Common Lisp snippets are read-only (no Lisp runtime on this site). JavaScript examples are labelled stand-ins that model the control flow.

block and return-from

block names a region; return-from leaves it immediately, lexically: the name must be visible in the source text.

LISP
(defun first-negative (numbers)
  (dolist (n numbers nil)
    (when (minusp n)
      (return-from first-negative n))))

(first-negative '(3 1 -4 1 -5))   ; => -4

Every defun implicitly wraps its body in a block with the function's name, so return-from function-name works as an early return. dolist, dotimes, loop and do establish a nil block, so (return x) is (return-from nil x).

A closure may use return-from for a block that is still active, even from inside a lambda called deeper in the stack:

LISP
(defun find-first (pred items)
  (block search
    (mapc (lambda (x) (when (funcall pred x) (return-from search x))) items)
    nil))

If the block has already exited, calling return-from on it is an error: the exit point is only valid while the block is active.

catch and throw

catch/throw is the dynamic counterpart: throw transfers to the most recent catch with an eq tag anywhere in the current call stack, regardless of lexical scope.

LISP
(defun deep (n)
  (if (zerop n)
      (throw 'done :bottom)
      (deep (1- n))))

(catch 'done (deep 10))   ; => :BOTTOM

Use catch for rare cases where the thrower and catcher cannot share lexical scope. Most of the time block is clearer, and conditions with restarts are better for recoverable situations. Throwing to a tag with no matching catch signals a control-error.

JS Stand-in: lexical versus dynamic exits

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

No output.

unwind-protect

unwind-protect evaluates a protected form, and then always runs the cleanup forms, however control leaves: normal return, return-from, throw, an error unwinding to a handler-case, even thread termination.

LISP
(defun call-with-lock (lock fn)
  (acquire lock)
  (unwind-protect (funcall fn)
    (release lock)))

The return value is that of the protected form. Cleanup forms should be short and must not themselves fail if possible; an error inside cleanup replaces the original exit. Standard macros like with-open-file and with-output-to-string are built from unwind-protect, as are the with- macros you wrote earlier.

One subtlety: cleanup runs during unwinding, after handlers have selected the exit point. With handler-bind plus invoke-restart, the handler runs first, then the restart unwinds, then cleanup forms execute. That ordering makes it safe to log in a handler and rely on cleanup afterwards.

JS Stand-in: cleanup order during unwinding

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

No output.

Assertions and type checks

Common Lisp has macros that check conditions and provide restarts:

LISP
(defun set-age (person age)
  (check-type age (integer 0 150) "a valid age")
  (setf (slot-value person 'age) age))

check-type signals a type-error with a store-value restart, so the debugger lets you enter a new value and continue. assert is the general form:

LISP
(assert (> (length name) 0) (name) "Name must not be empty: ~s" name)

The list (name) names the places the user may correct through the continue restart; assert then re-tests. Both are meant for programmer errors, not for validating external input you expect to be wrong sometimes. For user input, signal your own condition class and handle it.

ecase and etypecase are case/typecase that signal an error when nothing matches, preventing silent fall-through:

LISP
(defun speed-of (kind)
  (ecase kind
    (:walk 5)
    (:run 15)
    (:drive 60)))

(speed-of :fly)   ; error: :FLY fell through an ECASE expression

Plain case returns nil for an unknown key, which tends to hide bugs; prefer ecase unless you really want a default otherwise clause.

Declarations and safety

(declaim (optimize (safety 3))) makes the compiler check types and bounds fully, while (safety 0) removes checks and turns bugs into crashes. Keep the default (safety 1) until profiling says otherwise, and use assert and check-type at API boundaries.

Putting it together

A robust function combines the tools:

LISP
(defun read-config (path)
  (check-type path (or string pathname))
  (with-open-file (in path :if-does-not-exist nil)
    (unless in
      (error 'config-missing :path path))
    (loop for line = (read-line in nil)
          while line
          collect (parse-line line))))

check-type guards the programmer-error case, the :if-does-not-exist nil keeps a missing file from being an immediate opaque error, a domain condition is signaled instead, and with-open-file guarantees the file is closed.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does unwind-protect guarantee?

    Normal returns, return-from, throw and unwinding to a handler all run the cleanup forms.
  2. 2. What is the difference between return-from and throw?

    block names are lexical; catch tags are found at run time on the stack.
  3. 3. Why prefer ecase over case in many situations?

    ecase makes the 'impossible' case loud.
  4. 4. What restart does check-type provide?

    check-type offers store-value, so the debugger can prompt for a replacement and continue.

Summary

  • block/return-from is the lexical early exit; catch/throw is the dynamic one.
  • unwind-protect runs cleanup on every exit and underlies the with- macros.
  • check-type and assert check programmer errors and offer restarts; ecase/etypecase make missing cases loud.
  • Signal your own conditions for expected external failures.
  • Stand-ins in JavaScript only model the control-flow rules.

Next: Packages and ASDF Systems