Clojure not catching NumberFormatException

2019-02-22 12:05发布

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?

1条回答
趁早两清
2楼-- · 2019-02-22 12:45

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.

查看更多
登录 后发表回答