Clojure不捕获NumberFormatException [英] Clojure not catching NumberFormatException
问题描述
在下面的代码中,Clojure(1.2)正在打印错误的消息:
[value1,a]
(map#(Integer / parseInt%)(.split value,)))
(catch NumberFormatException _(printlnillegal argument)))
这应该打印非法参数,而是打印一个 ; NumberFormatException java.lang.NumberFormatException:对于输入字符串:a>
。
这是因为 map
返回的延迟序列吗?应该如何写?
<
try
特殊形式只捕获在正文代码的动态范围期间引发的异常。 map
正在返回一个延迟序列,然后从 try
特殊格式传递并返回,然后打印机评估 在中包含
应该可以解决您的问题。映射
doall
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.
这篇关于Clojure不捕获NumberFormatException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!