Error handling 如何在Common Lisp中异常后继续正常执行?

Error handling 如何在Common Lisp中异常后继续正常执行?,error-handling,common-lisp,sbcl,condition-system,Error Handling,Common Lisp,Sbcl,Condition System,我想捕捉未绑定变量异常并避免它们,在运行中创建一些变量而不中断执行。 我试图在以下代码中将处理程序绑定与调用重启一起使用: (defmacro my-progn (&rest rest) `(handler-bind ((unbound-variable (lambda (x) (progn ;(format t "UNBOUND VAR: ~a~%" ; (symbol-name (cell-error-

我想捕捉
未绑定变量
异常并避免它们,在运行中创建一些变量而不中断执行。 我试图在以下代码中将
处理程序绑定
调用重启
一起使用:

(defmacro my-progn (&rest rest)
  `(handler-bind
    ((unbound-variable
      (lambda (x)
        (progn
          ;(format t "UNBOUND VAR: ~a~%"
          ;  (symbol-name (cell-error-name x)))
          (invoke-restart 'just-continue)))))
    (progn ,@(mapcar (lambda (x)
                      `(restart-case ,x (just-continue () "XXXX"))) rest))))

(my-progn
  (print "AAA")
  (print xxxx) ;; xxxx is unbound
  (print "BBB"))

结果是:

"AAA"
"BBB" 
但是我想继续执行第二个
print
,只是将未绑定变量xxxx替换为字符串“xxxx”:

当然,我可以使用
处理程序bind
在语法树中包装任何符号,但我担心这会产生巨大的开销


是否有一种方法可以捕获
未绑定变量
异常,并使用动态生成的值而不是缺少的变量继续执行代码?

您可以使用适当的
使用值

(handler-bind
    ((unbound-variable
      (lambda (c)
        (declare (ignore c))
        (use-value "XXXX"))))
  (print "AAA")
  (print xxxx)
  (print "BBB"))

您可以使用适当的
使用值

(handler-bind
    ((unbound-variable
      (lambda (c)
        (declare (ignore c))
        (use-value "XXXX"))))
  (print "AAA")
  (print xxxx)
  (print "BBB"))

谢谢!我已经找到了使用(defvar)和(contiune)的解决方案,但是您的变体要好得多!谢谢!我已经找到了使用(defvar)和(contiune)的解决方案,但是您的变体要好得多!