【问题标题】:Handling Haskell exceptions with a single case clause?使用单个 case 子句处理 Haskell 异常?
【发布时间】:2014-06-14 22:45:45
【问题描述】:

考虑以下问题。

我正在为一些字符串函数编写包装器;其中之一是来自Data.Charchr(例如)。现在,如果我的 API 的输入是错误的输入,我想抛出一个错误,否则我只想返回整数输出。我想让算法保持简单——

getChr someInput = do
  x <- chr someInput -- this doesn't evaluate unless we evaluate ourselves
  -- handle exception here
  result = <_some_evaluation_>
  case result of
    Left  _ -> custom error throw
    Right _ -> return something

这显然不是任何 Haskell 代码,而是我希望算法看起来像的描述。我见过try (evaluate _) 的例子,但是那些返回IO (Either SomeException a) 类型的值我不确定是否可以用简单的case 语句来处理。我想要一些非常简单的东西,这样我就可以根据我的需要来处理它。有什么办法吗?

【问题讨论】:

    标签: exception haskell exception-handling monads


    【解决方案1】:

    try 很适合这个。

    getChr someInput = do
      x <- chr someInput
      result = try (some_evaluation x)
      case result of
        Left  (SomeException _) -> print "Oh no!"
        Right val               -> print val
    

    【讨论】:

      【解决方案2】:

      我猜你的问题可能是你只想捕获一些特定的异常,对吧?然后,您需要确保将异常投射到某个地方,以便它的类型比SomeException 更特别。例如:

      do
        result <- try something
        case result of
          Left  e  -> print (e :: IOException)
          Right x  -> return x
      

      或者,如果您想丢弃异常,请将其转换为 const

      do
        result <- try something
        case result of
          Left  e  -> const (print "whatever") (e :: IOException)
          Right x  -> return x
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-10-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多