[Haskell-cafe] Re: [Haskell] Catching error / making library functions monadic (in failure)

Duncan Coutts duncan.coutts at worc.ox.ac.uk
Wed Oct 8 13:20:32 EDT 2008

On Wed, 2008-10-08 at 18:07 +0200, Philip K.F. Hölzenspies wrote:

> I think this is the core problem I have. Really, error should be implemented 
> as fail, rather than vice versa. I see why this doesn't work, because it 
> would type
> error :: Monad m => String -> m a
> even though the whole idea is that it's typed 'a'.

Right, that's exactly why it would not work to give error that type.

However error should only be being used for programming errors, not for
expected runtime errors.

> Nonetheless, I would like 
> it if either IO wasn't the only monad allowing catching, or standard 
> functions not only being available with 'error' stuff (like !!, head, etc.).

Those functions do have safe counterparts for when you cannot guarantee
the pre-condition. It typically involves pattern matching, eg instead of
head use:

case foo of
  []     ->
  (x:xs) ->

Or for !! you could use take or splitAt and pattern matching.

If you want more exact analogues of head, !! etc then see Neil's Safe

> > If you can report them we can fix them.
> I think I spoke too soon. The error occur in other libraries' functions, so I 
> unjustly smudged your wonderful gtk2hs work (for which, btw: thanks very, 
> very much).

ok :-)

> To be honest; when I write a library, I also don't assume monadic 
> contexts for stuff that I do in purely functional terms. Sometimes errors 
> occur only in deeply nested code and "just putting in error" is the easy way 
> out. Especially, libraries that are not intended for "industrial strength" 
> production code seem to be prone to this type of coding, when they're not 
> already monadic.

I think it's not as bad as you suggest. In haskell, error is like
unchecked exceptions or assertions in Java. They are for cases that
really indicate a programmer error, not for bad input or IO failures.
Even these kinds of errors can be caught and contained in a sensible way
using exception handlers in IO.

For example supposing some web server page handler had some programming
error and called a function in a way that violated the pre-condition and
called error. That need not kill the entire server. The page handler
just needs to catch all exceptions and return a 500 internal server
error and write the error out to the logs. So it's actually a reasonably
robust way of dealing with the inevitable programmer errors.


More information about the Haskell-Cafe mailing list