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

How to capture (the type of) prelude exceptions?

假设我从 ghci 执行以下操作:

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

太棒了!现在我只需要以某种方式知道这个异常的类型(和模块)来编写一个异常处理程序。有什么办法可以得到所说的类型和模块吗?

我们知道 read 来自 Prelude。所以我们可以看看Prelude documentation for read on Hackage, which includes a source link。从那里,您可以继续单击看起来有错误的部分以跟随 read-error-errorCallException-ErrorCall 链并了解要捕获的适当异常是 GHC.Exception.ErrorCall。在 ghci 中测试:

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

似乎有效!

基于 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