简体   繁体   English

处理此特定的Haskell异常

[英]Handling this specific Haskell exception

I understand that in Control.Exception , you need the evaluate function to make sure that the expression first evaluates into something and then handle the exception using the handle function. 我了解在Control.Exception中 ,您需要evaluate函数以确保表达式首先评估为某些内容,然后使用handle函数处理异常。

Consider the following code below: 请考虑以下代码:

import Control.Exception
import System.Locale
import Data.Time

parseDay :: String -> String -> (Integer, Int, Int)
parseDay formatString dateString = toGregorian $ readTime defaultTimeLocale formatString dateString

Above is some code to parse dates in strings as its clear from the definition above. 上面是一些代码,用于解析字符串中的日期,正如上面定义所明确指出的那样。 This returns type (Integer, Int, Int) . 这将返回类型(Integer, Int, Int)

So, I am using the following line of code to see if there was an exception: 因此,我正在使用以下代码行来查看是否存在异常:

x = parseDay "%m" "-"
result = try (evaluate $ x) :: IO (Either SomeException (Integer, Int, Int))

In this case, the input is bad, so this throws the following exception: 在这种情况下,输入错误,因此将引发以下异常:

( * Exception: readsTime: bad input "-" *例外:readsT​​ime:错误的输入“-”

But the result is as follows: 但是结果如下:

Right ( * Exception: readsTime: bad input "-" 右( *例外:readsT​​ime:错误的输入“-”

which is something I cannot understand; 这是我无法理解的; it should be Left <error_message> as shown in all the examples I've seen. 如我所见的所有示例所示,它应该为Left <error_message> I am unsure, what is being lazy evaluated here and why this isn't working as desired. 我不确定,这里正在懒惰地评估什么,以及为什么它不能按预期工作。

I don't think evaluate is evaluating x deeply enough to reach the exception, so try is returning a Right result and the exception is only really evaluated when result is printed. 我认为evaluate并没有足够深入地评估x以达到异常,因此try返回Right结果,并且仅在打印result时才真正评估异常。

Try replacing the $ in parseDay with the strict $! 尝试更换$parseDay与严格$! and see if it works. 看看是否可行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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