如何在Clojure中捕获多个异常

如何在Clojure中捕获多个异常

本文介绍了如何在Clojure中捕获多个异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Clojure代码有一些java-interop,其中有一个抛出多个异常的方法。我希望与他们中的每个人打交道。根据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*)

它没有提到捕获多个异常。是否可以在Clojure中这样做?

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

谢谢!

推荐答案

与Java相同,你可以一个接一个地声明几个 catch 表达式,并且它们将按照它们声明的相同顺序进行匹配 - 首先 Exception1 ,如果它不匹配则 Exception2 依此类推,而最后部分将永远执行。

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")))

实际上,这是在文档中指定的,(尝试expr * catch-clause * finally-clause?)表示您可以将零个或多个表达式,零个或多个catch子句和零个或一个finally子句作为 try 表达式的一部分。

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.

这篇关于如何在Clojure中捕获多个异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 06:54