4

为什么此代码适用于

import qualified Control.OldException as E

但不与

import qualified Control.Exception as E

这是代码:

    fileContents <- (readFile "shpm.txt") `E.catch` (\_ -> return "")

这是我遇到的“新”异常错误

Ambiguous type variable `e0' in the constraint:
  (E.Exception e0) arising from a use of `E.catch'
Probable fix: add a type signature that fixes these type variable(s)
In a stmt of a 'do' block:
  fileContents <- (readFile "shpm.txt")
                  `E.catch` (\ _ -> return "No Tasks")
4

2 回答 2

9

因为种类变了。具体来说:

  • 旧异常:catch :: IO a -> (Exception -> IO a) -> IO a
  • 例外:catch :: Exception e => IO a -> (e -> IO a) -> IO a

新模型需要知道e该类型的值是什么Exception e。这实际上意味着您需要告诉编译器您正在捕获哪个异常。您的示例OldException捕获了所有内容,现在不鼓励这样做(有关更多信息,请参阅捕获所有异常)。

对您的功能的简单修复将是这样的:

foo = (readFile "foo") `E.catch` (\e -> const (return "") (e :: E.IOException))

或无 lambda 版本:

bar = (readFile "foo") `E.catch` myHandler

myHandler :: E.IOException -> IO String
myHandler _ = return ""
于 2012-09-07T05:23:12.427 回答
1

您需要为被捕获的异常提供显式类型。例如:

fileContents <- (readFile "shpm.txt") `E.catch` ((\_ -> return "") :: E.SomeException -> IO String)
于 2012-09-07T05:21:29.460 回答