catching exceptions in haskell


I was going to go to bed earlier, but there’s that one thing bugging me and it’s Haskell exceptions. During one of my previous adventures with Haskell errors I struggled with handling them graciously in quickckeck properties. Then I read about exceptions vs. errors, discovered that errors are probably not the best choice in expected, probable scenarios and suddenly wanted to start experimenting with exceptions.

No time to waste, let’s do some reading and write a “Hello World!” program for exceptions.

Reading material:

After some reading I managed to formulate my first exception throwing and catching piece of code:

{-#LANGUAGE DeriveDataTypeable#-}

import Control.Exception
import Data.Typeable (Typeable)

data HelloWorldException = HelloWorldException deriving (Show, Typeable)

instance Exception HelloWorldException

troublemaker :: Int -> IO ()
troublemaker x = if x == 0 then throw HelloWorldException else putStrLn $ show x

main :: IO ()
main = do
	catch (troublemaker 0) (\e -> putStrLn $ "Caught " ++ show (e :: HelloWorldException))
	catch (troublemaker 1) (\e -> putStrLn $ "Caught " ++ show (e :: HelloWorldException))

Output:

Caught HelloWorldException
1

Which does work (well, does throw and does catch…) but I’m yet to discover if this is the way to deal with exceptions. For now it will suffice.

Now to use exceptions in practice! But that’s a story for another day.

Happy hacking!