Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 "" ?

like image 384
ocodo Avatar asked Aug 31 '13 01:08

ocodo


1 Answers

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

like image 184
Barmar Avatar answered Nov 10 '22 17:11

Barmar