How to catch multiple exceptions in Clojure?

前端 未结 1 917
心在旅途
心在旅途 2021-02-13 23:59

My Clojure code has some java-interop with a method that throws multiple exceptions. I wish to deal with each individual of them. According to Clojure documentation:

<         


        
1条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-14 00:13

    It's the same as in Java, you can declare several catch expressions one after the other, and they'll get matched in the same order they were declared - first Exception1, if it doesn't match then Exception2 and so on, and the finally part will always be executed.

    (try 
        (catch Exception1 e1 (prn "in catch1"))
        (catch Exception2 e2 (prn "in catch2"))
        (finally (prn "in finally")))
    

    In fact, this is specified in the documentation, (try expr* catch-clause* finally-clause?) means that you can have "zero or more expressions", "zero or more catch clauses" and "zero or one finally clauses" as part of a try expression.

    0 讨论(0)
提交回复
热议问题