moondaisy
moondaisy

Reputation: 4491

Check if function returned an error in Haskell

I want to create a function that returns True when a function throws any kind of exception and False if it doesn't.

But I haven't been able to figure out a way to do this with the catch method at Control.Exception.

I want to catch the error thrown by [1,2] !! 3 but also custom errors thrown by the usage of error "Error msg".

Upvotes: 2

Views: 1238

Answers (1)

chi
chi

Reputation: 116139

You can use catch as follows:

example :: IO ()
example = do
   let handler :: SomeException -> IO Bool
       handler e = do
          putStrLn "Exception caught:"
          print e
          return False
   res <- (evaluate ([1,2::Int] !! 3) >> return True) `catch` handler
   print res

The last print will print True on normal termination, and False on exceptional termination.

The output messages in the handler can be removed -- they're only for illustration.

You can replace SomeException with any more specific exception type, if you only want to catch some of them.

Note that you can't catch exceptions outside IO, which makes them more limited. For that reason partial functions like !! should be avoided, preferring functions returning a Maybe a type instead, whose output can be checked anywhere.

Upvotes: 8

Related Questions