Emacs lisp - 如何尝试/ catch处理错误?

oco*_*odo 5 emacs error-handling elisp

在以下defun ...

(defun re-backward-match-group (rexp &optional n)
  "Grab the previous matches of regexp and return the contents of
  the n match group (first group match if no n arg is specified)"
  (save-excursion
  (unless n
    (setq n 1))
  (when (numberp n)
    (when (re-search-backward-lax-whitespace rexp)
      (when  (= (+ 2 (* n 2)) (length (match-data)))
        (match-string-no-properties n))))))
Run Code Online (Sandbox Code Playgroud)

如果未找到匹配项,则会引发错误 re-search-backward-lax-whitespace

我如何捕获该错误并返回nil或""

Bar*_*mar 3

re-search-backward-lax-whitespace有一个可选noerror参数。

(re-search-backward-lax-whitespace rexp nil t)
Run Code Online (Sandbox Code Playgroud)

不会发出错误信号。

对于更一般的错误处理,您可以使用ignore-errorscondition-case。有关后者的信息,请参见

Emacs Lisp 中的错误处理