开发者

Catch custom exception in Clojure

开发者 https://www.devze.com 2023-04-12 19:43 出处:网络
In the libphonenumber library, the PhoneNumberUtil.parse function throws a NumberParseException. I\'d like to handle this exception gracefully.

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

开发者_C百科(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


Just like PhoneNumberUtil, You need to either import the NumberParseException 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).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号