Why doesn't my code throw an exception?

{-# 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 is my program not printing "Msg"?

Update:

I changed the code:

io :: IO ()
io = catch (return t) (\e -> putStrLn $ myExToString e)

main = io >>= print

But my code did not catch MyException? Why?

+4
source share
2 answers

Since Haskell is lazy and you never use the result t, therefore it is never evaluated and thus the exception is not thrown.

+9
source

About "Why does the code below not throw an exception?":

io :: IO ()
io = catch (return t) (\e -> putStrLn $ myExToString e)

main = io >>= print

It printthrows an exception if it forces you to tevaluate, but at that time there isn’t catch. Try instead:

io :: IO ()
io = catch (return t >>= print) (\e -> putStrLn $ myExToString e)
    -- or simply:  catch (print t) (\e -> ....)
main = io
+3
source

All Articles