【问题标题】:Haskell IO error handling during IO operationIO操作期间的Haskell IO错误处理
【发布时间】:2014-04-19 16:42:52
【问题描述】:

System.Directory 库中,getPermissions 函数可能会返回 IO 错误。 文档说它可能会因isPermissionErrorisDoesNotExistError 而失败。 调用getPermissions时出现IO错误如何处理?

尝试:

input <- try (do 
        permissions <- getPermissions filepath 
        print permissions)
case input of
        Left e  -> print "a"
        Right e -> print "b"

错误:

No instance for (Exception e0) arising from a use of ‘try’
The type variable ‘e0’ is ambiguous
Note: there are several potential instances:
  instance Exception NestedAtomically
    -- Defined in ‘Control.Exception.Base’
  instance Exception NoMethodError
    -- Defined in ‘Control.Exception.Base’
  instance Exception NonTermination
    -- Defined in ‘Control.Exception.Base’
  ...plus 7 others
In a stmt of a 'do' block:
  input <- try
             (do { permissions <- getPermissions filepath;
                   print permissions })
In the expression:
  do { input <- try
                  (do { permissions <- getPermissions filepath;
                        print permissions });
       case input of {
         Left e -> print "a"
         Right e -> print "b" } }
In an equation for ‘checkwritefilepermissions’:
    checkwritefilepermissions filepath
      = do { input <- try
                        (do { permissions <- getPermissions filepath;
                              print permissions });
             case input of {
               Left e -> print "a"
               Right e -> print "b" } }

【问题讨论】:

    标签: haskell error-handling io


    【解决方案1】:

    错误消息表明无法确定要捕获的异常类型(即Exception 的实例)。一种可能的解决方案是提供一个类型注释来指定它,如:

    case (input :: Either IOError String) of
        Left e -> print "a"
        Right r -> print "b"
    

    或者,如果您使用isDoesNotExistErrorSystem.IO.Error 中的朋友来区分错误情况,则异常类型将被推断为IOError,而不需要额外的注释。

    可以在the Control.Exception documentation 中找到有关基本异常捕获实践的相关讨论。

    【讨论】:

      【解决方案2】:

      这个问题有一个简单的解决方法(不是最好的解决方法),替换

      Left e
      

      通过

      Left (e :: SomeException)
      

      顺便说一句,你的代码可以这样简化

      input <- try $ getPermissions filepath
      case input of
          Left (e :: SomeException) -> print "a"
          Right e -> print "b"
      

      而且您确实应该改进代码中的这些名称。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-05-01
        • 1970-01-01
        • 2012-05-26
        • 2019-03-28
        • 1970-01-01
        • 2010-11-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多