2015-10-20 56 views
2

我正在学习如何在Haskell中使用异常。
当试图复制在前奏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),当我以前有一个例外?

+2

问题是** GHCi **不知道'e0'的类型,所以你必须告诉:'尝试(打印x):: IO(ArithException()) - 原因是在编译时有很多可能的实例(对于不同的例外:[见这里](https://hackage.haskell.org/package/) base-4.8.1.0/docs/Control-Exception-Base.html#t:Exception) - 和GHCi不能选择) – Carsten

+3

(当然你也可以总是使用'SomeException') – Carsten

+0

@Carsten谢谢 – Ionut

回答

6

问题是,哈斯克尔/ GHCI不知道的e0的类型,所以你必须将其标注为:

try (print x) :: IO (Either ArithException()) 

的原因是,在编译时有相当多的可能实例(不同的例外):see here for a description - 和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)) 

当然

你不必猜测正确的异常(如做了与ArithException) - 而不是你可以使用SomeException所有太:

Prelude Control.Exception> try (print x) :: IO (Either SomeException()) 
Left divide by zero 
相关问题