Answers:
我们有许多选择。
您可以catch/ throw退出功能。
例:
(defun my-func ()
"thrown error"
(catch 'my-catch
(when t
(throw 'my-catch "always going to throw"))
(+ 42 1)))
您还可以使用block和return-from(尽管需要cl-macs)
例:
(require 'cl-macs)
(defun my-func ()
"block / return-from"
(block my-func
(when t
(return-from my-func))
(+ 42 1)))
我们也有cl-defun一个具有block与函数同名的隐式函数,因此我们可以block减少样式。
例:
(require 'cl-macs)
(cl-defun my-func ()
"cl-defun implicit block"
(when t
(return-from my-func)) ; my-func is an implicit block.
(+ 42 1)))
cl-defun也可以用作别名defun*,其定义cl.el如下:
(require 'cl)
(defun* my-func ()
"defun* implicit block"
(when t
(return-from my-func)) ; my-func is an implicit block.
(+ 42 1)))
除了@EmacsFodder涵盖的内容以外,只需引发一个错误。
如果在错误处理结构(例如ignore-errors或)的范围内(动态地而非词法地)调用代码,这将无济于事condition-case,但否则,这是退出函数的一种好方法。实际上,大多数情况下都是这样做的。
(defun my-func ()
"..."
(unless something (error "Whoops!"))
; continue as usual...
(+ 42 1))
如果您想自己处理错误,则可以将调用代码(例如,对最终调用的内容的调用my-func)放在A中condition-case。同样,这是大多数情况下执行的操作,至少与使用catch+相同throw。这完全取决于您想要的行为。
catch/throw会在elisp中更加惯用,因为其他方法最终都是在catch / throw方面实现的。在elisp的手册说:“大多数其他版本的Lisp语言,包括Common Lisp的,有非顺序传送控制的几种方法:return,return-from,和go,例如的Emacs Lisp只throw。”