Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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".

like image 511
moondaisy Avatar asked May 11 '26 07:05

moondaisy


1 Answers

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.

like image 138
chi Avatar answered May 13 '26 20:05

chi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!