ocodo
ocodo

Reputation: 30269

Emacs lisp - how to try/catch handle an error?

In the following 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))))))

If no match is found, an error is thrown by re-search-backward-lax-whitespace

How would I catch that error and return nil or "" ?

Upvotes: 6

Views: 3198

Answers (1)

Barmar
Barmar

Reputation: 781814

re-search-backward-lax-whitespace has an optional noerror argument.

(re-search-backward-lax-whitespace rexp nil t)

will not signal an error.

For more general error handling, you can use ignore-errors or condition-case. For information on the latter, see

Error Handling in Emacs Lisp

Upvotes: 3

Related Questions