在 Clojure 中捕获自定义异常
在 libphonenumber 库中,PhoneNumberUtil.parse
函数会抛出 <代码>NumberParseException。我想优雅地处理这个异常。
我正在运行以下一次性脚本(使用 java -cp path/to/clojure.jar:path/to/libphonenumber.jar clojure.main -i scrap.clj 调用):
(import '(com.google.i18n.phonenumbers PhoneNumberUtil))
(defn parse-phone-no
"Convert the phone number to standard form, using the libphonenumber class.
Arguments:
raw-phone-no - the phone number to convert
Returns:
the canonical version of the phone number, or nil if the phone number was
invalid."
[raw-phone-no]
(do
(def phone-util (PhoneNumberUtil/getInstance))
(try
(do
(def us-number (.parse phone-util raw-phone-no "US"))
(.getNationalNumber us-number))
(catch NumberParseException e
nil))))
(println (parse-phone-no "5"))
如果我使用通用 catch Exception
运行它,然后它可以正常工作,但是 catch NumberParseException
、catch PhoneNumberUtil/NumberParseException
和catch (.NumberParseExceptionphoneUtil)
给出无法解析类名
错误。我想捕获自定义异常并让其他人滑动,因此我将感谢您的帮助。
谢谢,凯文
In the libphonenumber library, the PhoneNumberUtil.parse
function throws a NumberParseException
. I'd like to handle this exception gracefully.
I'm running the following one-off script (invoked with java -cp path/to/clojure.jar:path/to/libphonenumber.jar clojure.main -i scratch.clj
):
(import '(com.google.i18n.phonenumbers PhoneNumberUtil))
(defn parse-phone-no
"Convert the phone number to standard form, using the libphonenumber class.
Arguments:
raw-phone-no - the phone number to convert
Returns:
the canonical version of the phone number, or nil if the phone number was
invalid."
[raw-phone-no]
(do
(def phone-util (PhoneNumberUtil/getInstance))
(try
(do
(def us-number (.parse phone-util raw-phone-no "US"))
(.getNationalNumber us-number))
(catch NumberParseException e
nil))))
(println (parse-phone-no "5"))
If I run it with a generic catch Exception
then it works fine, however any combination of catch NumberParseException
, catch PhoneNumberUtil/NumberParseException
, and catch (.NumberParseException phoneUtil)
gives a Unable to resolve classname
error. I'd like to catch the custom exception and let others slide, so I'd appreciate your help.
Thanks, Kevin
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
就像
PhoneNumberUtil
一样,您需要将NumberParseException
导入
到命名空间,或者在catch表达式中提供其完整限定包。如果例外是内部类,则在 clojure 中将其转换为 OuterClass$InnerClass (您仍然需要导入或使用其包进行限定)。
Just like
PhoneNumberUtil
, You need to eitherimport
theNumberParseException
to the namespace or provide its full qualified package in the catch expression.If the exception is an inner class, that translates in clojure to OuterClass$InnerClass (which you still need to either import or qualify with its package).