Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't my code catch Exception?

Tags:

haskell

{-# 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?

like image 822
ZhekaKozlov Avatar asked Dec 14 '22 15:12

ZhekaKozlov


2 Answers

Because Haskell is lazy, and you never use the result of t, so it is never evaluated and thus the exception isn't thrown.

like image 94
Sebastian Redl Avatar answered Dec 23 '22 09:12

Sebastian Redl


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
like image 28
chi Avatar answered Dec 23 '22 07:12

chi