{-# LANGUAGE DeriveDataTypeable #-}
import Control.Exception
import Data.Typeable
data MyException = MyException String deriving (Show, Typeable)
instance Exception MyException
myExToString :: MyException -> String
myExToString (MyException msg) = msg
t :: ()
t = throw $ MyException "Msg"
main = catch (return t) (\e -> putStrLn $ myExToString e)
Why doesn't my program print "Msg"?
Update:
I changed the code:
io :: IO ()
io = catch (return t) (\e -> putStrLn $ myExToString e)
main = io >>= print
But still my code doesn't catch MyException? Why?
Because Haskell is lazy, and you never use the result of t, so it is never evaluated and thus the exception isn't thrown.
About "why the code below does not print the exception?":
io :: IO ()
io = catch (return t) (\e -> putStrLn $ myExToString e)
main = io >>= print
Here, print is causing the exception to be thrown when it forces t to be evaluated, but at that time there's no catch around. Try instead:
io :: IO ()
io = catch (return t >>= print) (\e -> putStrLn $ myExToString e)
-- or simply: catch (print t) (\e -> ....)
main = io
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With