TExcelTAD
Home › Haskell › Haskell Error Handling

Haskell Error Handling

Haskell has two kinds of error handling, and knowing which to use is half the skill:

  1. Errors as values: Maybe, Either and ExceptT. 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.
  2. 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

haskell · try it yourself
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

haskell · try it yourself
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:

haskell · try it yourself
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:

haskell · try it yourself
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:

haskell · try it yourself
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:

haskell · try it yourself
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 SomeException broadly 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))?

  1. try only works with evaluate
  2. Because of laziness: without forcing, the division happens later, outside try
  3. To make it faster
  4. div is an IO action

What should you use for an invalid value typed by a user?

  1. error
  2. throwIO
  3. Either with a descriptive error type
  4. undefined

What does bracket acquire release use guarantee?

  1. use never fails
  2. release runs even if use throws an exception
  3. Exceptions are ignored
  4. acquire is retried