user972946
user972946

Reputation:

How to catch multiple exceptions in Clojure?

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:

(try expr* catch-clause* finally-clause?)
catch-clause -> (catch classname name expr*)

it has no mention of catching multiple exceptions. Is it possible to do so in Clojure?

Thank you!

Upvotes: 13

Views: 5478

Answers (1)

Óscar López
Óscar López

Reputation: 236004

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 <some code>
    (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.

Upvotes: 26

Related Questions