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

dsi*_*ign 4 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
Run Code Online (Sandbox Code Playgroud)

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

chi*_*chi 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
Run Code Online (Sandbox Code Playgroud)