- Create a new project exceptions with the simple Stack template.
- Open src/Main.hs and edit it.
- After the module declaration, add the following imports for Exception and for doing IO:
import qualified Control.Exception as E import System.IO
- 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
- 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 ...