

Generalised error handling in Haskell - samstokes
http://www.randomhacks.net/articles/2007/03/10/haskell-8-ways-to-report-errors

======
samstokes
As mentioned in <http://news.ycombinator.com/item?id=986586>, this was one of
two blog posts that convinced me that Haskell was worth looking at.

To summarise the part of this post that made the biggest impression on me, it
shows how a function _f_ can be written in such a way that it can report
errors in case of failure, but leaves the choice of how to handle those errors
_entirely up to the caller_. If _f_ is called within a _catch_ expression, it
will throw an exception if it fails. If you're expecting an error message
back, it'll return one. If it's called in the Maybe monad, it'll return
Nothing. You can even implement your own custom error handling strategy in
your code (e.g. collect errors and keep going), and _f_ will play along,
without having to change its source code.

This only works because of Haskell's expressive type system and pervasive type
inference. (Pervasive as opposed to, say, Scala, which infers some types but
requires explicit annotation for others.)

Seems to me these are utterly practical use cases, and they constitute real
ammunition for the static typing lobby.

~~~
lincolnq
I like this too, but it's worth noting two things:

1) this is from 2007

2) Real World Haskell (which is authored in part by dons) recommends against
using fail, and it's much more recent.

From <http://book.realworldhaskell.org/read/monads.html> :

 _Warning - Beware of fail_

 _Many Monad instances don't override the default implementation of fail that
we show here, so in those monads, fail uses error. Calling error is usually
highly undesirable, since it throws an exception that callers either cannot
catch or will not expect._

 _Even if you know that right now you're executing in a monad that has fail do
something more sensible, we still recommend avoiding it. It's far too easy to
cause yourself a problem later when you refactor your code and forget that a
previously safe use of fail might be dangerous in its new context._

~~~
samstokes
Thanks for stomping on my dreams. :P

In any case, Haskell's not the only institution that's tried to deprecate
_fail_ :

<http://news.bbc.co.uk/1/hi/england/suffolk/4724703.stm>

