如何捕获(类型)前奏异常?

时间:2015-11-04 10:13:25

标签: haskell exception-handling ghc

说我从ghci执行以下操作:

   Prelude Control.Exception Data.Typeable> let a = read "A" :: Int
   Prelude Control.Exception Data.Typeable> a
   *** Exception: Prelude.read: no parse

大!现在我只需要以某种方式知道此异常的类型(和模块)来编写异常处理程序。有没有办法得到所说的类型和模块?

2 个答案:

答案 0 :(得分:8)

以Daniel Wagner的回答为基础:

import Control.Exception
import Data.Typeable

whichException :: IO a -> IO ()
whichException act = do
  e <- try act
  case e of
    Left (SomeException ex) -> print $ typeOf ex
    _                       -> putStrLn "No exception occurred"

-- Usage:
-- > whichException (evaluate (read "A"::Int))
-- ErrorCall

答案 1 :(得分:4)

我们知道read来自Prelude。我们可以查看Prelude documentation for read on Hackage,其中包含source link。在那里,您可以继续点击看错误的部分,以关注read - error - errorCallException - ErrorCall链,并了解捕获的相应异常是GHC.Exception.ErrorCall。在ghci中进行测试:

> try (evaluate (read "A")) :: IO (Either ErrorCall Int)
Left Prelude.read: no parse

似乎工作!