[Haskell-beginners] Catching Exceptions in Haskell

Bjoern Brandenburg bbb.lst at gmail.com
Sat Feb 28 15:57:41 EST 2009


Hi all,

I'm struggling to figure out how to catch an exception in Haskell.

Eventually, what I want to do is to use the Control.Macho library
(from Hackage) to parse binaries on Mac OS X. Naturally, I would like
my program to gracefully handle corrupted files or files that aren't
binaries. So I need to catch exceptions if the parsing with Data.Macho
fails...

This is what I've got so far:
http://hpaste.org/fastcgi/hpaste.fcgi/view?id=1877#a1877

Digression: Note that if I leave out the `foo e` call, then I get

scratch.hs:21:9:
    Ambiguous type variable `e' in the constraint:
      `Exception e' arising from a use of `try' at scratch.hs:21:9-11
    Probable fix: add a type signature that fixes these type variable(s)

I find this somewhat counter-intuitive; this is also not discussed in
the book "Real-World Haskell" (at least I haven't found it), which is
what I'm using to learn Haskell. What is the best way to get around
this?

Back to my problem. The program produces the following output:

$ runghc scratch.hs
Testing Pure... Caught a bad exception: abort via error
Testing Macho... No exception occured, the result is:
scratch.hs: too few bytes. Failed reading at byte position 4

This counter-intuitive in at least two ways:

1) How can it fail at position 4 in an empty string? That looks like a
sloppy error message too me; why doesn't it report the actually
failing position?

2) Why can I catch an exception raised with an error in my own code,
but not the one raised by Data.Binary.Get? Looking at
http://hackage.haskell.org/packages/archive/binary/0.5/doc/html/src/Data-Binary-Get.html#failDesc
, an exception within Data.Binary.Get is also raised with error. What
is the difference?

Why am I seeing what I'm seeing, and how should I be doing it in the
first place?

Thanks in advance,
Bjoern


More information about the Beginners mailing list