异常类型错误

Ion*_*nut 2 haskell

我正在学习Haskell中的异常如何工作.
当试图在Prelude中复制这个简单的例子时,我得到:

GHCi, version 7.10.2: http://www.haskell.org/ghc/  :? for help
Prelude> :m Control.Exception
Prelude Control.Exception> let x = 5 `div` 0
Prelude Control.Exception> let y = 5 `div` 1
Prelude Control.Exception> print x
*** Exception: divide by zero
Prelude Control.Exception> print y
5
Prelude Control.Exception> try (print x)

<interactive>:16:1:
    No instance for (Show (IO (Either e0 ())))
      arising from a use of `print'
    In a stmt of an interactive GHCi command: print it
Prelude Control.Exception>
Run Code Online (Sandbox Code Playgroud)

为什么我得到任何情况下错误try(print x),当我以前有一个例外?

Car*_*ten 6

问题是Haskell/GHCi不知道类型,e0所以你必须注释它:

try (print x) :: IO (Either ArithException ()) 
Run Code Online (Sandbox Code Playgroud)

原因是在编译时有很多可能的实例(对于不同的例外):请参阅此处的描述 - 而GHCi无法选择

你可以得到GHCI告诉你,所以如果你看起来有点更深的表情(或多或少不直接强迫GHCIshow它):

Prelude Control.Exception> e <- try (print x)

<interactive>:5:6:
    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 the first argument of `GHC.GHCi.ghciStepIO ::
                                IO a_a18N -> IO a_a18N', namely
      `try (print x)'
    In a stmt of an interactive GHCi command:
      e <- GHC.GHCi.ghciStepIO :: IO a_a18N -> IO a_a18N (try (print x))
Run Code Online (Sandbox Code Playgroud)

当然你不必猜错正确的异常(正如所做的那样ArithException) - 相反你也可以SomeException用来捕捉所有异常:

Prelude Control.Exception> try (print x) :: IO (Either SomeException ())
Left divide by zero
Run Code Online (Sandbox Code Playgroud)