【问题标题】:How can I throw an exception in Clojure?如何在 Clojure 中抛出异常?
【发布时间】:2011-07-24 12:15:19
【问题描述】:

我希望抛出一个异常并有以下内容:

(throw "Some text")

但它似乎被忽略了。

【问题讨论】:

  • throw 抛出 Java Throwable 的实例。 (throw (Exception. "Some text")) 有效吗?
  • 当我尝试(抛出“一些文本”)时,我得到一个 ClassClassException,因为 String 无法转换为 Throwable。因此,在您的情况下,投掷被“忽略”很奇怪....

标签: exception exception-handling clojure functional-programming


【解决方案1】:

你需要将你的字符串包裹在Throwable:

(throw (Throwable. "Some text"))

(throw (Exception. "Some text"))

您也可以设置 try/catch/finally 块:

(defn myDivision [x y]
  (try
    (/ x y)
    (catch ArithmeticException e
      (println "Exception message: " (.getMessage e)))
    (finally 
      (println "Done."))))

REPL 会话:

user=> (myDivision 4 2)
Done.
2
user=> (myDivision 4 0)
Exception message:  Divide by zero
Done.
nil

【讨论】:

    【解决方案2】:

    clojure.contrib.condition 提供了一种对 Clojure 友好的异常处理方法。你可以提出有原因的条件。每个条件都可以有自己的处理程序。

    source on github中有很多例子。

    它非常灵活,您可以在提升时提供自己的键、值对,然后根据键/值决定在处理程序中做什么。

    例如(修改示例代码):

    (if (something-wrong x)
      (raise :type :something-is-wrong :arg 'x :value x))
    

    然后您可以为:something-is-wrong 提供处理程序:

    (handler-case :type
      (do-non-error-condition-stuff)
      (handle :something-is-wrong
        (print-stack-trace *condition*)))
    

    【讨论】:

    【解决方案3】:

    如果您想抛出异常并在其中包含一些调试信息(除了消息字符串),您可以使用内置的ex-info 函数。

    要从之前构建的 ex-info 对象中提取数据,请使用 ex-data

    来自 clojuredocs 的示例:

    (try
      (throw 
        (ex-info "The ice cream has melted!" 
           {:causes             #{:fridge-door-open :dangerously-high-temperature} 
            :current-temperature {:value 25 :unit :celcius}}))
      (catch Exception e (ex-data e))
    

    在评论中,kolen 提到了slingshot,它提供了高级功能,不仅允许您抛出任意类型的对象(使用 throw+),还可以使用更灵活的 catch 语法来检查抛出对象中的数据(使用 try+) .来自the project repo的例子:

    张量/parse.clj

    (ns tensor.parse
      (:use [slingshot.slingshot :only [throw+]]))
    
    (defn parse-tree [tree hint]
      (if (bad-tree? tree)
        (throw+ {:type ::bad-tree :tree tree :hint hint})
        (parse-good-tree tree hint)))
    

    数学/表达式.clj

    (ns math.expression
      (:require [tensor.parse]
                [clojure.tools.logging :as log])
      (:use [slingshot.slingshot :only [throw+ try+]]))
    
    (defn read-file [file]
      (try+
        [...]
        (tensor.parse/parse-tree tree)
        [...]
        (catch [:type :tensor.parse/bad-tree] {:keys [tree hint]}
          (log/error "failed to parse tensor" tree "with hint" hint)
          (throw+))
        (catch Object _
          (log/error (:throwable &throw-context) "unexpected error")
          (throw+))))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-24
      • 2011-02-22
      • 2020-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多