Errors and exception handling
We have been looking at Maybe
and Either
in earlier recipes and used them for conveying error. For example, Nothing :: Maybe a
conveys that the evaluation has resulted in an error, and that is how we now have Nothing
. Either is more informative than Maybe
and conveys more information through its Left
constructor.
In this recipe, we will work with three situations:
- Working with error and catching it later
- Working with IO exception and catching it
- Creating a custom exception, raising it, and catching it
How to do it...
- Create a new project
exceptions
with thesimple
Stack template. - Open
src/Main.hs
and edit it. - After the module declaration, add the following imports for
Exception
and for doingIO
:
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 thedivision by zero
situation, we use theerror :: String -> a
function to raise an error. This function takes...