异常类型错误

时间:2015-10-20 20:14:12

标签: haskell

我正在学习Haskell中异常的工作原理 在Prelude中尝试复制this简单示例时,我得到:

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>

为什么我在try(print x)上遇到无实例错误,之前我遇到异常?

1 个答案:

答案 0 :(得分:6)

问题是Haskell / GHCi 不知道var array = [1,2,4,223,53,6,1]; var total = 0; for( i = 0; i < array.length; i++ ) { total += i; } 的类型,所以你必须注释它:

e0

原因是在编译时有很多可能的实例(针对不同的例外):see here for a description - 和 GHCi 无法选择

你可以让GHCi告诉你如果你看一下表达式(或多或少不直接强迫 GHCi try (print x) :: IO (Either ArithException ()) ):

show

当然,您不必猜测正确的异常(正如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)) 所做的那样) - 相反,您可以使用ArithException catch

SomeException
相关问题