
Untitled
By: a guest on
Jun 17th, 2012 | syntax:
None | size: 1.08 KB | hits: 13 | expires: Never
Exception handling in Haskell
x = 5 `div` 0
test = try (print x) :: IO (Either SomeException ())
main = do
result <- try (evaluate (5 `div` 0)) :: IO (Either SomeException Int)
case result of
Left ex -> putStrLn $ "Caught exception: " ++ show ex
Right val -> putStrLn $ "The answer was: " ++ show val
main = catch (print $ 5 `div` 0) handler
where
handler :: SomeException -> IO ()
handler ex = putStrLn $ "Caught exception: " ++ show ex
main = do
result <- tryJust selectDivByZero (evaluate $ 5 `div` 0)
case result of
Left what -> putStrLn $ "Division by " ++ what
Right val -> putStrLn $ "The answer was: " ++ show val
where
selectDivByZero :: ArithException -> Maybe String
selectDivByZero DivideByZero = Just "zero"
selectDivByZero _ = Nothing
do handle (NonTermination -> exitWith (ExitFailure 1)) $ ...
let handler = handle (NonTermination -> exitWith (ExitFailure 1))
do
let result = 5 `div` 0
let handler = (_ -> print "Error") :: IOException -> IO ()
catch (print result) handler