From d7741a3374a28b37fc989f7b53c8e7065a9ec3d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ga=C3=ABl=20Depreeuw?= Date: Sun, 17 Jun 2018 13:16:05 +0200 Subject: [PATCH] Complete chapter 30 --- .../30-when-things-go-wrong.md | 5 +++++ .../src/StoppingTheParty.hs | 21 +++++++++++++++++++ 2 files changed, 26 insertions(+) create mode 100644 30-when-things-go-wrong/30-when-things-go-wrong.md create mode 100644 30-when-things-go-wrong/src/StoppingTheParty.hs diff --git a/30-when-things-go-wrong/30-when-things-go-wrong.md b/30-when-things-go-wrong/30-when-things-go-wrong.md new file mode 100644 index 0000000..b2a0d41 --- /dev/null +++ b/30-when-things-go-wrong/30-when-things-go-wrong.md @@ -0,0 +1,5 @@ +# 30 When things go wrong + +## 30.5 The unbearable imprecision of trying + +see [src/StoppingTheParty.hs](./src/StoppingTheParty.hs) \ No newline at end of file diff --git a/30-when-things-go-wrong/src/StoppingTheParty.hs b/30-when-things-go-wrong/src/StoppingTheParty.hs new file mode 100644 index 0000000..cef2c5e --- /dev/null +++ b/30-when-things-go-wrong/src/StoppingTheParty.hs @@ -0,0 +1,21 @@ +module StoppingTheParty where + +import Control.Concurrent(threadDelay) +import Control.Exception +import Control.Monad (forever) +import System.Random (randomRIO) + +randomException :: IO () +randomException = do + i <- randomRIO (1, 10 :: Int) + if i `elem` [1..9] + then throwIO DivideByZero + else throwIO StackOverflow + +main :: IO () +main = forever $ do + let tryS :: IO () -> IO (Either SomeException ()) + tryS = try + _ <- tryS randomException + putStrLn "Live to loop another day!" + threadDelay (1 * 1000000) \ No newline at end of file