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
exceptionswith thesimpleStack template. - Open
src/Main.hsand edit it. - After the module declaration, add the following imports for
Exceptionand for doingIO:
import qualified Control.Exception as E
import System.IO- We will write a function
div1to divide one integer by another. However, when we encounter thedivision by zerosituation, we use theerror :: String -> afunction to raise an error. This function takes...