[Haskell-cafe] A program which never crashes (even when a function calls "error")

Clifford Beshers clifford.beshers at linspire.com
Tue Aug 1 18:04:10 EDT 2006

Stephane Bortzmeyer wrote:
> [It is a philosophical question, not a practical programming problem.]
> I'm used, in imperative programming languages with exceptions (like
> Python) to call any function without fear of stopping the program
> because I can always catch the exceptions with things like (Python):
> while not over:
>    try: 
>       code which may raise an exception...
>    except Exception e:
>       do something clever
> How to do it in Haskell? How can I call functions like Prelude.head
> while being sure my program won't stop, even if I call head on an
> empty list (thus calling "error")?
Here's another way of looking at it, that I've grown fond of.

If your program is a total function, then there should be no exceptions.

That is, if you properly model the world, in all its messiness, then you 
can write a function that maps every instance of the world to some valid 
output, even if that output is ``Sorry.''

It might seem a daunting task, but liberal use of the Maybe class from 
the ground up helps.  We have suffered through quite a bit of this with 
our hardware detector, where unexpected situations are the norm.  My 
colleague David Fox has spent considerable time computing reasonable 
answers in seemingly impossible situations, to the point where you 
cannot turn around without bumping into a Maybe construct.

More information about the Haskell-Cafe mailing list