2015-10-20 64 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 
相關問題