2011-10-11 46 views
0

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 NumberParseExceptioncatch PhoneNumberUtil/NumberParseExceptioncatch (.NumberParseException phoneUtil)組合給出Unable to resolve classname錯誤。我想趕上自定義異常並讓其他人滑動,所以我會很感激您的幫助。

謝謝,凱文

+0

你也應該考慮用'let'而不是'def'來創建局部變量(在這種情況下,「考慮」的意思是:「絕對做到這一點,但如果你仍然在學習Clojure,你可以暫時擱置一段時間「)。令人驚訝的是,我現在找不到一個SO問題來聯繫你:抱歉。 – amalloy

+0

也許問一個問題並自己回答?因爲是的,我知道我的語法真的很糟糕。 –

回答

4

就像PhoneNumberUtil,你需要或者importNumberParseException命名空間或在catch表達提供其全部合格的包裝。

如果該異常是內部類,它將在clojure中轉換爲OuterClass $ InnerClass(您仍然需要導入或使用它的包限定)。