O'Reilly logo

Haskell Cookbook by Yogesh Sajanikar

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How to do it...

  1. Create a new project exceptions with the simple Stack template.
  2. Open src/Main.hs and edit it.
  3. After the module declaration, add the following imports for Exception and for doing IO:
        import qualified Control.Exception as E
        import System.IO
  1. We will write a function div1 to divide one integer by another. However, when we encounter the division by zero situation, we use the error :: String -> a function to raise an error. This function takes and raises SomeException:
        div1 :: Int -> Int -> Int
        div1 x 0 = error "Division by zero"
        div1 x y = x `div` y
  1. Now, we will write safeDiv1 and safeDiv2 , which will catch the exception and will safely show the result of the division:
 safeDiv1 :: Int -> Int -> IO () safeDiv1 x y = E.catch ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required