Clojure不捕获NumberFormatException [英] Clojure not catching NumberFormatException

查看:158
本文介绍了Clojure不捕获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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆