Chuyển đến nội dung

Bài 31 · Condition System

Restarts: Recovering Without Unwinding

Master Common Lisp restarts: restart-case, invoke-restart, with-simple-restart, use-value and continue, and how low-level code offers recovery choices while policy lives higher up.

Exceptions in most languages answer "something went wrong; unwind to here". Common Lisp adds a second question: "what are the ways to carry on?" A restart is a named recovery point established by the code that knows how to recover, while a handler in the code that knows which recovery is appropriate picks one. That separation is the signature feature of the Lisp condition system.

Lisp snippets are read-only (no Common Lisp runtime on this site). The JavaScript examples are labelled stand-ins modeling the restart mechanism.

The problem restarts solve

Imagine a log-parsing library. When it hits a malformed line, what should it do: skip it, stop, substitute a default, ask the user? The library does not know; the application does. Throwing an exception forces the library to give up. With restarts, the library keeps its context (position, open files) and offers options.

restart-case

LISP
(define-condition malformed-entry (error)
  ((text :initarg :text :reader text)))

(defun parse-entry (line)
  (if (find #\: line)
      (let ((pos (position #\: line)))
        (cons (subseq line 0 pos) (subseq line (1+ pos))))
      (restart-case (error 'malformed-entry :text line)
        (skip-entry ()
          :report "Skip this entry."
          nil)
        (use-value (v)
          :report "Use a replacement entry."
          v))))

restart-case wraps an expression and defines named restarts. Each restart has a lambda list, an optional :report string (shown in the debugger) and a body that runs in the context of the restart-case, so its result becomes the value of the whole form. parse-entry knows how to skip or substitute; it does not decide.

Choosing a restart in a handler

Code higher in the stack picks a restart with invoke-restart inside a handler-bind:

LISP
(defun parse-all (lines)
  (handler-bind ((malformed-entry
                   (lambda (c)
                     (declare (ignore c))
                     (invoke-restart 'skip-entry))))
    (remove nil (mapcar #'parse-entry lines))))

(parse-all '("a:1" "oops" "b:2"))
;; => (("a" . "1") ("b" . "2"))

The handler runs at the point of the error, on top of the signaling stack, invokes skip-entry, and control returns to the restart-case inside parse-entry for the bad line. The mapping carries on with the next line: the loop was never abandoned. Different callers can choose different policies without changing the parser:

LISP
(handler-bind ((malformed-entry
                 (lambda (c) (invoke-restart 'use-value (cons "?" (text c))))))
  (mapcar #'parse-entry '("a:1" "oops")))
;; => (("a" . "1") ("?" . "oops"))
JS Stand-in: restarts and handlers

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

No output.

Standard restarts

Several restarts are built in and widely used:

Restart Established by Effect
abort the REPL / top level return to the top level
continue cerror, continue function proceed after a correctable error
use-value check-type, ecase, assert... and your code supply a replacement value
store-value check-type, assert store a new value in the place
muffle-warning warn suppress a warning

(cerror "Continue anyway" "Disk is ~a% full" 98) signals an error but establishes a continue restart. use-value and store-value are the reason that the debugger offers "enter a new value" for failed check-type.

Convenience functions find and invoke them: (use-value 5), (continue), (abort), (muffle-warning) call the nearest restart of that name if one exists (and return NIL if not, except for abort/muffle-warning which signal an error). compute-restarts lists the active ones and find-restart tests for one.

LISP
(handler-bind ((error (lambda (c)
                        (declare (ignore c))
                        (let ((r (find-restart 'use-value)))
                          (when r (invoke-restart r 0))))))
  (parse-integer "oops" :junk-allowed nil))

(Here parse-integer does not establish use-value, so find-restart returns NIL and the error continues to the debugger. Always test for a restart you do not control.)

with-simple-restart

For the common "skip this item" case, with-simple-restart establishes a restart that returns (values nil t):

LISP
(defun process-all (items)
  (dolist (item items)
    (with-simple-restart (skip-item "Skip ~a." item)
      (process item))))

If process signals an error in the interactive debugger, the programmer sees "Skip ITEM-3." as an option and the loop continues with the next item. This single macro turns many fatal errors into recoverable ones during development.

Interactive restarts

A restart can prompt for its arguments with :interactive:

LISP
(restart-case (error "Bad config")
  (use-value (v)
    :report "Use a different value."
    :interactive (lambda () (list (read)))
    v))

In the debugger the user selects the restart, is prompted, and execution proceeds. Long-running programs can be fixed during an error without restarting: change the data, choose a restart, and carry on.

When to use what

Situation Tool
failure is unrecoverable here, caller should decide error plus handler-case upstream
failure is recoverable in more than one way restart-case in the low-level code, policy in handler-bind
skip-on-failure while developing with-simple-restart
log and continue handler-bind that logs, then declines or invokes a restart

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Who defines restarts and who chooses among them?

    Low-level code offers options (restart-case); high-level policy picks one (invoke-restart in a handler).
  2. 2. Why must invoke-restart usually be called from handler-bind rather than handler-case?

    Restarts live on the signaling stack; handler-bind runs before unwinding, so they are still established.
  3. 3. What does with-simple-restart establish?

    It is the shortcut for a restart that simply abandons the wrapped form.
  4. 4. What is the benefit of :report in a restart clause?

    The text appears in the list of restarts shown by the debugger.

Summary

  • A restart is a named recovery point; restart-case defines it where the knowledge is.
  • Handlers on top of the signaling stack choose with invoke-restart (or helpers like use-value).
  • Standard restarts include abort, continue, use-value, store-value and muffle-warning.
  • with-simple-restart makes "skip this item" recovery cheap.
  • This separation of mechanism and policy is what exceptions alone cannot provide.

Next: Non-Local Exits, Assertions and Cleanup

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.