条件系统:error! / with-handlers / restart
发信号、handler 返回即 decline、invoke-restart 恢复,以及 try / catch 与 unwind-protect。
error! 发信号(条件用符号命名);condition? 检查。
(defun validate [n]
(if (or (not (integer? n)) (< n 0))
(error! 'bad-age n)
n))
(validate 42)
with-handlers 的 handler 返回即 decline——条件继续外传。
(with-handlers ((bad-age (fn [c] :declining-only)))
(validate -5))
恢复 = handler 内 invoke-restart + restart-case 声明策略。find-restart 探测可用 restart。
(with-handlers ((bad-age (fn [c] (invoke-restart 'use-value 0))))
(restart-case (validate -5)
(use-value (fallback) fallback)))
try/catch 是简化的兜底形状:错误串绑定在 *error*。
(try (validate -1) (catch error (println *error*)))
形状决策:(catch e ...) 会把 e 当类型名而永不匹配——第一位置必须是条件类型名。
unwind-protect 保证清理段运行。
(unwind-protect
:body
(println "cleanup ran"))