# Haskell Error Monad Example

type classes)Safe HaskellSafeLanguageHaskell98Control.Monad.ErrorContentsMonads with error handlingThe ErrorT monad transformerExample 1: Custom Error Data TypeExample 2: Using ErrorT Monad TransformerDescriptionDeprecated: Use Control.Monad.Except insteadComputation type:Computations which may fail or throw exceptions.Binding strategy:Failure records throwerror haskell information about the cause/location of the failure. Failure values bypass

## Monaderror Example

the bound function, other values are used as inputs to the bound function.Useful for:Building computations from haskell eithert sequences of functions that may fail or using exception handling to structure error handling.Zero and plus:Zero is represented by an empty error and the plus operation

## Monadthrow

executes its second argument if the first fails.Example type:`Either String a`

The Error monad (also called the Exception monad).Synopsisclass Monad m => MonadError e m | m -> e wherethrowError :: e -> m acatchError :: m a -> (e -> m a) -> m aclass Error a wherenoMsg :: astrMsg :: String haskell either type -> anewtype ErrorT e m a :: * -> (* -> *) -> * -> * = ErrorT {runErrorT :: m (Either e a)}runErrorT :: ErrorT e m a -> m (Either e a)mapErrorT :: (m (Either e a) -> n (Either e' b)) -> ErrorT e m a -> ErrorT e' n bmodule Control.Monadmodule Control.Monad.Fixmodule Control.Monad.TransMonads with error handlingclass Monad m => MonadError e m | m -> e where SourceThe strategy of combining computations that can throw exceptions by bypassing bound functions from the point an exception is thrown to the point that it is handled.Is parameterized over the type of error information and the monad type constructor. It is common to use `Either String`

as the monad type constructor for an error monad in which error descriptions take the form of strings. In that case and many other common cases the resulting monad is already defined as an instance of the

## Haskell Fail

handling and exceptions. When we speak of "pure" error handling, we are referring to algorithms that do not require anything from haskell mtl the IO monad. We can often implement error handling for them by simply using Haskell's expressive data type system to our advantage. Haskell also has an exception system. Due to the complexities of lazy evaluation, https://hackage.haskell.org/package/mtl/docs/Control-Monad-Error.html exceptions in Haskell can be thrown anywhere, but only caught within the IO monad. In this chapter, we'll consider both. Error Handling with Data Types Let's begin our discussion of error handling with a very simple function. Let's say that we wish to perform division on a series of numbers. We have a constant numerator, but wish to vary the denominator. We might come up with a function like this: -- http://book.realworldhaskell.org/read/error-handling.html file: ch19/divby1.hs divBy :: Integral a => a -> [a] -> [a] divBy numerator = map (numerator `div`) Very simple, right? We can play around with this a bit in ghci: ghci> divBy 50 [1,2,5,8,10] [50,25,10,6,5] ghci> take 5 (divBy 100 [1..]) [100,50,33,25,20] This behaves as expected: 50 / 1 is 50, 50 / 2 is 25, and so forth. [38] This even worked with the infinite list [1..]. What happens if we sneak a 0 into our list somewhere? ghci> divBy 50 [1,2,0,8,10] [50,25,*** Exception: divide by zero Isn't that interesting? ghci started displaying the output, then stopped with an exception when it got to the zero. That's lazy evaluation at work—it calculated results as needed. As we will see later in this chapter, in the absence of an explicit exception handler, this exception will crash the program. That's obviously not desirable, so let's consider better ways we could indicate an error in this pure function. Use of Maybe One immediately-recognizable easy way to indicate failure is to use Maybe.[39] Instead of just returning a list and throwing an exception on failure, we can return Nothing if the input list contained a zero anywhere, or Just with the results otherwise. Here's an implementation of such an algorithm: -- fi

22 Aug 2013 Michael Snoyman View Markdown source Next content: Catching all exceptions Go up to: Exceptions See all content by Michael Snoyman Sections The simple case: https://www.schoolofhaskell.com/user/snoyberg/general-haskell/exceptions/exceptions-and-monad-transformers the ReaderT transformerFirst complication: mutable stateSecond complication: alternative exit pathsmonad-controlMore intuitive mutable state John Wiegley and I are currently working- together with some members of the community- on various exception handling related code. http://watchchrislearn.com/blog/2013/11/29/playing-with-the-either-monad/ As part of this work, we're also going to be publishing a number of tutorials on this topic. Eventually, we'll collect all of this information together into a more cohesive whole, but for haskell error now we wanted to get the content out there to the community as we produce it.Love them or hate them, runtime exceptions are a reality of writing Haskell code. Consider the following fake code:myFunc = do resource <- acquireScarceResource useResource resource releaseResource resourceIn a world without exceptions, this seems completely reasonable. However, what happens if the call to useResource throws a runtime exception? In such a case, haskell error monad releaseResource would never be called, and our scarce resource would never be released. In concurrent code dealing with mutexes, such a bug could lead to a deadlock.The solution to this problem is well known: use the bracket function. Then our above example reduces to myFunc = bracket acquireScarceResource releaseResource useResource. We're now safe from any exception thrown by useResource, and even from asynchronous exceptions (a topic I'll try to avoid in this post).But let's analyze the type signature of bracket:bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO cHow do we use such a function in monad transformer stack, where the functions we pass in won't live in the IO monad itself?Note that for the rest of this tutorial, I'm going to talk about the finally function instead of bracket, which is really just a simplified version of the latter. The reasoning used will apply to not only bracket, but also to many other functions in Control.Exception. Its signature is IO a -> IO b -> IO a, and its purpose is to ensure that the second function is called regardless of what exceptions are thrown by the first (or any asyn