Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture (the type of) prelude exceptions?

Say I do the following from ghci:

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

Great! Now I just need to somehow know the type (and the module) of this exception to write an exception handler. Is there any way to get said type and module?

like image 539
dsign Avatar asked Dec 15 '22 10:12

dsign


1 Answers

Built upon Daniel Wagner's answer:

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
like image 138
chi Avatar answered Dec 26 '22 10:12

chi