[Haskell-cafe] Catching string from error function with GHC Control.Exception

Andrew Savige ajsavige at yahoo.com.au
Sun Jan 1 07:53:18 EST 2006

I am a Haskell beginner, using GHC 6.4.1.

Suppose I have a function, tt, say, which may call error.
For the purposes of testing tt, I'd like to be able to catch
the error string and assert that it matches the expected error
string. Is HUnit or QuickCheck (or either) the appropriate tool
for this sort of testing?

I managed to get it working with HUnit, but it's horribly kludgy
mainly because I'm yet to grok monads. The little test program
below demonstrates my question outside of HUnit:

import Control.Exception

tt :: String -> Int
tt s = error ("hi error '" ++ s ++ "'")
-- tt s = read s

ttWrap :: String -> IO String
ttWrap x = do let r = tt x
              -- comment out next line, error string not caught
              putStr (show r)
              return (show r)

ttWrap2 :: IO String
ttWrap2 = do res <- tryJust errorCalls (ttWrap "123")
             case res of
               Right r  -> return (show r)
               Left  r  -> return r

main = do x <- ttWrap2
          putStrLn ("caught:" ++ x)
          y <- ttWrap2
          putStrLn ("caught:" ++ y)

When you run the above test program, it does indeed catch the
error string thrown by the tt function (and prints it out in
main). However, if you comment out the putStr line as shown in
the comment above, it no longer catches the error string, but
dies instead. Why?

I'm sure there is a cleaner way to achieve what I'm trying to
do and I'd appreciate advice on the best way to do this.


Send instant messages to your online friends http://au.messenger.yahoo.com 

More information about the Haskell-Cafe mailing list