Skip to content

Instantly share code, notes, and snippets.

@CMCDragonkai
Last active April 9, 2019 12:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CMCDragonkai/d1d61680c0eebaf6345cde63c0828f50 to your computer and use it in GitHub Desktop.
Save CMCDragonkai/d1d61680c0eebaf6345cde63c0828f50 to your computer and use it in GitHub Desktop.
Haskell Exceptions (only to be used with IO) #haskell
-- safe-exceptions Control.Exception.Safe > exceptions Control.Monad.Catch > base Control.Exception
import Control.Exception.Safe
import Control.Monad.IO.Class (MonadIO, liftIO)
data WhatException = ThisError
| ThatError
deriving (Show)
instance Exception WhatException
doThis :: IO String
doThis = do
line <- getLine
if null line then throw ThisError
else if line == "f" then throw ThatError
else return line
doThatWithCatch :: IO String
doThatWithCatch = do
line <- catch
doThis
(\e -> case (e :: WhatException) of
ThisError -> return "recovered this"
ThatError -> return "recovered that")
return $ line ++ "!"
doThatWithTry :: IO String
doThatWithTry = do
line <- try doThis
case line of
(Left ThisError) -> return "recovered this!"
(Left ThatError) -> return "recovered that!"
(Right line') -> return $ line' ++ "!"
doThisGeneric :: (MonadIO m) => m String
doThisGeneric = do
line <- liftIO getLine
if null line then liftIO $ throw ThisError
else if line == "f" then liftIO $ throw ThatError
else return line
doThatGeneric :: (MonadIO m) => m String
doThatGeneric = do
line <- liftIO $ catch doThisGeneric handle
return $ line ++ "!"
where
handle :: (MonadIO m) => WhatException -> m String
handle e = case e of
ThisError -> return "recovered this"
ThatError -> return "recovered that"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment