在libphonenumber庫中,PhoneNumberUtil.parse
函數拋出NumberParseException
。我想優雅地處理這個異常。在Clojure中捕獲自定義異常
我跑以下一次性腳本(使用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"))
如果我有一個通用的catch Exception
運行它,然後它工作正常,但是任何的catch NumberParseException
,catch PhoneNumberUtil/NumberParseException
和catch (.NumberParseException phoneUtil)
組合給出Unable to resolve classname
錯誤。我想趕上自定義異常並讓其他人滑動,所以我會很感激您的幫助。
謝謝,凱文
你也應該考慮用'let'而不是'def'來創建局部變量(在這種情況下,「考慮」的意思是:「絕對做到這一點,但如果你仍然在學習Clojure,你可以暫時擱置一段時間「)。令人驚訝的是,我現在找不到一個SO問題來聯繫你:抱歉。 – amalloy
也許問一個問題並自己回答?因爲是的,我知道我的語法真的很糟糕。 –