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

Dimitry Golubovsky golubovsky at gmail.com
Tue Sep 7 09:45:10 EDT 2010


Thanks to everybody who replied.

I see another solution: are there any hidden problems?

I found an interesting package, ChasingBottoms which contains a
function testing a value to be bottom and returning a Boolean (of
course it cannot be done without unsafePerformIO).

I borrowed the idea from that package, and wrote two functions:

unThrow :: (Exception e) => a -> Either e a

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

So, if there is a value inside the lazy list which is a bottom (binary
parse failure of the last received object in this case, catching any
possible exception) then the value can be converted to Nothing within
pure code, and then excluded from the result using catMaybes.

This solution seems to be working for me.

PS Maybe the way I am using the serialized data needs to be changed by
implementing some kind of an iterator over the binary stream, and then
by taking one object at a time and consuming it right there the
problem might be eliminated entirely...

Thanks again.

Dimitry Golubovsky

Anywhere on the Web

More information about the Haskell-Cafe mailing list