[Haskell-cafe] How to catch exception within the Get monad (the Binary package)

Ben Millwood haskell at benmachine.co.uk
Tue Sep 7 18:47:19 EDT 2010

On Tue, Sep 7, 2010 at 2:45 PM, Dimitry Golubovsky <golubovsky at gmail.com> wrote:
> unThrow a = unsafePerformIO $ (E.evaluate a >>= return . Right) `E.catch`
>                                               (\e -> return $ Left e)
> -- or perhaps the right argument of catch could be just (return . Left)?
> bm2mb :: a -> Maybe a
> bm2mb a = case unThrow a of
>   Left (e::SomeException) -> Nothing
>   Right a -> Just a

Philosophically these functions are Nasty because they violate
referential transparency. In particular it's possible for the same
expression to throw different exceptions each time it's run depending
on how it's optimised, what other threads are doing, if the user
presses ctrl-C, etc. etc.
See the spoon package:


which alleviates this a little by only catching some kinds of
exception, and not telling you which it caught. It still violates
monotonicity (I believe), so purists will be upset, but practically it
can be useful for when editing the source code to provide explicit
exceptions (which is ideally what you'd do) is not an option.

More information about the Haskell-Cafe mailing list