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)
,當我以前有一個例外?
問題是** GHCi **不知道'e0'的類型,所以你必須告訴:'嘗試(打印x):: IO(ArithException()) - 原因是在編譯時有很多可能的實例(對於不同的例外:[見這裏](https://hackage.haskell.org/package/) base-4.8.1.0/docs/Control-Exception-Base.html#t:Exception) - 和GHCi不能選擇) – Carsten
(當然你也可以總是使用'SomeException') – Carsten
@Carsten謝謝 – Ionut