{-# 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)
为什么我的程序不打印"Msg"
?
更新
我更改了代码:
io :: IO ()
io = catch (return t) (\e -> putStrLn $ myExToString e)
main = io >>= print
但我的代码仍然没有抓住MyException
?为什么呢?
答案 0 :(得分:9)
因为Haskell是惰性的,并且你从不使用t
的结果,所以它永远不会被评估,因此不会抛出异常。
答案 1 :(得分:3)
关于“以下代码为何不打印例外?”:
io :: IO ()
io = catch (return t) (\e -> putStrLn $ myExToString e)
main = io >>= print
此处,print
导致在强制t
进行评估时抛出异常,但当时没有catch
。请尝试改为:
io :: IO ()
io = catch (return t >>= print) (\e -> putStrLn $ myExToString e)
-- or simply: catch (print t) (\e -> ....)
main = io