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
Digression: Note that if I leave out the `foo e` call, then I get
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
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
Apparently the exception is only triggered when m is used in line 31.
So I guess that evaluate in line 24 is not causing strict evaluation
of the Data.Binary.Get monad, even though it is working for the error
and assert tests.
Why is that? Is that expected? If so, what am I doing wrong?
Now the 2nd exception won't be raised either: evaluate digged one
level into assert, and that causes an exception, but return will not
do that, it will just return the unevaluated thunk that wraps the
assert computation, and this thunk will get evaluated when you print
You can get the behavior what you expect by using some functions from
(res :: Either SomeException String) <- try $?evaluate?(f x `using` rnf)
Now all 3 will throw an exception, as you expected.?Why? (a `using`
rnf) reduces its argument (a) to "head normal form", which basically
means it evaluating all sub-expressions at all levels.
> evaluate (1:error "2": `using` rnf) >>= print . head
will now give an error.
On Sun, Mar 1, 2009 at 1:48 AM, Bjoern Brandenburg <[hidden email]> wrote:
> Ok, so I was able to extract a simpler program with the same symptoms.
> http://hpaste.org/fastcgi/hpaste.fcgi/view?id=1900#a1900 >
> Apparently the exception is only triggered when m is used in line 31.
> So I guess that evaluate in line 24 is not causing strict evaluation
> of the Data.Binary.Get monad, even though it is working for the error
> and assert tests.
> Why is that? Is that expected? If so, what am I doing wrong?
> Beginners mailing list
> [hidden email] > http://www.haskell.org/mailman/listinfo/beginners