简体   繁体   中英

Clojure not catching NumberFormatException

In the following code, Clojure (1.2) is printing the wrong message:

(try
  (let [value "1,a"]
    (map #(Integer/parseInt %) (.split value ",")))
  (catch NumberFormatException _ (println "illegal argument")))

This should print "illegal argument", but instead it prints a (1#<NumberFormatException java.lang.NumberFormatException: For input string: "a"> .

What am I doing wrong?

Is this because of the lazy sequence returned by map ? How should it be written?

The try special form only catches exceptions that are raised during during the dynamic extent of the body code. Here map is returning a lazy sequence, which then is passed out of the try special form and returned. The printer then evaluates the sequence, and at that point the exception is thrown.

Wrapping the map in doall should fix your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM