Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 17th, 2012  |  syntax: None  |  size: 1.08 KB  |  hits: 13  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Exception handling in Haskell
  2. x = 5 `div` 0
  3. test = try (print x) :: IO (Either SomeException ())
  4.        
  5. main = do
  6.     result <- try (evaluate (5 `div` 0)) :: IO (Either SomeException Int)
  7.     case result of
  8.         Left ex  -> putStrLn $ "Caught exception: " ++ show ex
  9.         Right val -> putStrLn $ "The answer was: " ++ show val
  10.        
  11. main = catch (print $ 5 `div` 0) handler
  12.   where
  13.     handler :: SomeException -> IO ()
  14.     handler ex = putStrLn $ "Caught exception: " ++ show ex
  15.        
  16. main = do
  17.     result <- tryJust selectDivByZero (evaluate $ 5 `div` 0)
  18.     case result of
  19.         Left what -> putStrLn $ "Division by " ++ what
  20.         Right val -> putStrLn $ "The answer was: " ++ show val
  21.   where
  22.     selectDivByZero :: ArithException -> Maybe String
  23.     selectDivByZero DivideByZero = Just "zero"
  24.     selectDivByZero _ = Nothing
  25.        
  26. do handle (NonTermination -> exitWith (ExitFailure 1)) $ ...
  27.        
  28. let handler = handle (NonTermination -> exitWith (ExitFailure 1))
  29.        
  30. do      
  31.     let result = 5 `div` 0
  32.     let handler = (_ -> print "Error") :: IOException -> IO ()
  33.     catch (print result) handler