我一直在尝试在 Clojure 中创建用户定义的异常,但遇到了各种各样的问题。我尝试了这里概述的方法:
http://en.wikibooks.org/wiki/Clojure_Programming/Concepts#User-Defined_Exceptions http://en.wikibooks.org/wiki/Clojure_Programming/Concepts#User-Defined_Exceptions
(gen-and-load-class 'user.MyException :extends Exception)
但这似乎在 Clojure 1.2 中不起作用(或者我做错了什么......)。我的环境是 Clojure 1.2、Emacs 和 lein swank。
感谢您的帮助!
除了生成自定义类之外,还有两种更简单的方法来使用自定义异常:
Use 弹弓 https://github.com/scgilardi/slingshot- 这提供了定制throw+
and catch+
允许您抛出和捕获任何对象以及异常的宏。
在 Clojure 1.4 及更高版本中,您可以使用clojure.core/ex-info http://clojure.github.io/clojure/clojure.core-api.html#clojure.core/ex-info and clojure.core/ex-data http://clojure.github.io/clojure/clojure.core-api.html#clojure.core/ex-data生成并捕获clojure.lang.ExceptionInfo
类,它包装消息和数据映射。
使用它很简单:
(throw (ex-info "My hovercraft is full of eels"
{:type :python-exception, :cause :eels}))
(try (...)
(catch clojure.lang.ExceptionInfo e
(if (= :eels (-> e ex-data :cause))
(println "beware the shrieking eels!")
(println "???"))))
或者在 midje 测试中:
(fact "should throw some eels"
(...)
=> (throws clojure.lang.ExceptionInfo
#(= :eels (-> % ex-data :cause))))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)