Search code examples
functionemacselispexit

How to exit from a function at any arbitrary point, in elisp


This is a simple question, but somehow I couldn't find an answer by googling:

How do you exit a function at any arbitrary point of execution, if some condition is not met. For example (I use "(exit)" as a substitute here):

(defun foo ()
  (progn (if (/= a1 a2)
             (exit) ; if a1!=a2, exit the function somehow
           t)
         (blahblah...)))

Solution

  • In elisp, you can use catch and throw instead of cl's block and return-from.

    (defun foo ()
      (catch 'my-tag
        (when (not (/= a1 a2))
          (throw 'my-tag "non-local exit value"))
        "normal exit value"))
    

    See C-hig (elisp) Nonlocal Exits RET