Haskell Error Handling
Haskell has two kinds of error handling, and knowing which to use is half the skill:
- Errors as values:
Maybe,EitherandExceptT. The possibility of failure is in the type, and the compiler makes callers deal with it. This is the default for anything you can anticipate, such as invalid input or a missing key. - Exceptions: thrown and caught in
IO. They are for truly exceptional situations, mostly from the outside world (a missing file, a lost network connection) or from bugs (head [], division by zero).
Errors as values: a quick recap
import Text.Read (readMaybe)
data ParseError = Empty | NotANumber String | Negative Int
deriving Show
parseQuantity :: String -> Either ParseError Int
parseQuantity "" = Left Empty
parseQuantity s = case readMaybe s of
Nothing -> Left (NotANumber s)
Just n
| n < 0 -> Left (Negative n)
| otherwise -> Right n
main :: IO ()
main = do
mapM_ (print . parseQuantity) ["12", "", "twelve", "-3"]
print (traverse parseQuantity ["1", "2", "3"])
print (sum <gt; traverse parseQuantity ["1", "x", "3"])Right 12
Left Empty
Left (NotANumber "twelve")
Left (Negative (-3))
Right [1,2,3]
Left (NotANumber "x")
Callers see from the type that parsing can fail, and the custom error type lists precisely how.
Converting between Maybe and Either
import Data.Maybe (fromMaybe)
note :: e -> Maybe a -> Either e a
note err Nothing = Left err
note _ (Just x) = Right x
hush :: Either e a -> Maybe a
hush (Left _) = Nothing
hush (Right x) = Just x
main :: IO ()
main = do
let ages = [("ann", 31), ("bob", 45)]
print (note "unknown user" (lookup "ann" ages))
print (note "unknown user" (lookup "eve" ages))
print (hush (Left "bad" :: Either String Int), hush (Right 3 :: Either String Int))
print (either (const 0) (* 2) (note "x" (lookup "bob" ages)))
print (fromMaybe 0 (lookup "eve" ages))Right 31
Left "unknown user"
(Nothing,Just 3)
90
0
note and hush are tiny helpers many projects define (or import from a utility package) to move between the two types.
Exceptions in IO
Some failures can't be predicted from pure types: the disk is full, the file was deleted. These are thrown as exceptions, and you catch them in IO with try or catch from Control.Exception:
import Control.Exception
import System.IO.Error (isDoesNotExistError)
readConfig :: FilePath -> IO (Either String String)
readConfig path = do
result <- try (readFile path) :: IO (Either IOException String)
return $ case result of
Left e
| isDoesNotExistError e -> Left ("no such file: " ++ path)
| otherwise -> Left ("could not read " ++ path)
Right contents -> Right contents
main :: IO ()
main = do
writeFile "/tmp/app.conf" "port=8080\n"
readConfig "/tmp/app.conf" >>= print
readConfig "/tmp/missing.conf" >>= print
r <- try (readFile "/tmp/missing.conf")
case r of
Left e -> putStrLn ("raw message: " ++ show (e :: IOException))
Right _ -> putStrLn "unexpected"Right "port=8080\n"
Left "no such file: /tmp/missing.conf"
raw message: /tmp/missing.conf: openFile: does not exist (No such file or directory)
try turns an exception into an Either, which brings us back to errors as values. The type annotation picks which exceptions to catch: here IOException. Others pass through.
Exceptions from pure code
Pure code can throw too, with error, partial functions like head, or arithmetic like div 1 0. Because of laziness, such an exception only fires when the value is evaluated, so you must force it inside try with evaluate:
import Control.Exception
main :: IO ()
main = do
r1 <- try (evaluate (10 `div` (0 :: Int)))
case r1 of
Left DivideByZero -> putStrLn "caught division by zero"
Left other -> putStrLn ("other arithmetic error: " ++ show other)
Right v -> print v
r2 <- try (evaluate (error "invalid state" :: Int))
case r2 of
Left (ErrorCall msg) -> putStrLn ("caught error call: " ++ msg)
Right v -> print v
r3 <- try (evaluate (length [1, 2, 3])) :: IO (Either SomeException Int)
print (either (const (-1)) id r3)caught division by zero
caught error call: invalid state
3
Without evaluate, try (return (div 10 0)) would succeed, returning an unevaluated thunk, and the exception would explode later, outside the try.
Throwing your own exceptions
Define a type, make it an instance of Exception, and throw it with throwIO:
import Control.Exception
data BankError = InsufficientFunds Int | AccountLocked String
deriving Show
instance Exception BankError
withdraw :: Int -> Int -> IO Int
withdraw balance amount
| amount > balance = throwIO (InsufficientFunds (amount - balance))
| otherwise = return (balance - amount)
main :: IO ()
main = do
b <- withdraw 100 30
print b
result <- try (withdraw 100 250)
case result of
Left (InsufficientFunds short) -> putStrLn ("short by " ++ show short)
Left (AccountLocked who) -> putStrLn (who ++ " is locked")
Right newBalance -> print newBalance
handle (\e -> putStrLn ("handled: " ++ show (e :: BankError))) $ do
_ <- throwIO (AccountLocked "acct-7")
putStrLn "not reached"70
short by 150
handled: AccountLocked "acct-7"
handle is catch with the arguments flipped, which reads well with a do block.
Cleaning up: finally and bracket
When an action acquires a resource (a file handle, a lock, a connection), make sure it is released even if an exception occurs:
import Control.Exception
main :: IO ()
main = do
r <- try $
bracket
(putStrLn "open connection" >> return "conn-1") -- acquire
(\c -> putStrLn ("close " ++ c)) -- release, always runs
(\c -> do -- use
putStrLn ("using " ++ c)
_ <- evaluate (1 `div` (0 :: Int))
putStrLn "never printed")
putStrLn ("result: " ++ either (\e -> "failed with " ++ show (e :: ArithException)) (const "ok") r)
(putStrLn "work" `finally` putStrLn "cleanup")open connection
using conn-1
close conn-1
result: failed with divide by zero
work
cleanup
withFile from System.IO is a ready-made bracket for files.
Which one should I use?
| Situation | Use |
|---|---|
| Invalid user input, a failed lookup, business rule violated | Maybe / Either (or ExceptT) |
| File, network, or OS problems | catch IOException at the I/O boundary, convert to Either |
| A bug, an impossible state | let it crash (error), then fix the code |
| Releasing resources | bracket, finally, withFile |
Warning: Avoid catching
SomeExceptionbroadly in real code: it also catches things like thread cancellation and Ctrl-C (asynchronous exceptions). Catch the specific exception types you can actually handle.
Test yourself
Why is evaluate needed in try (evaluate (div 1 0))?
tryonly works withevaluate- Because of laziness: without forcing, the division happens later, outside
try - To make it faster
divis an IO action
What should you use for an invalid value typed by a user?
errorthrowIOEitherwith a descriptive error typeundefined
What does bracket acquire release use guarantee?
usenever failsreleaseruns even ifusethrows an exception- Exceptions are ignored
acquireis retried