Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 57 ยท IO and the real world

Exceptions and Error Handling

Handle failure in Haskell: choose between Maybe, Either and exceptions, use throwIO, catch, try, bracket and ExceptT, and define custom exceptions.

Things go wrong: a file is missing, input is malformed, a number is divided by zero. Haskell gives you two families of tools. Errors as values (Maybe, Either, ExceptT) show up in the types, so the compiler makes callers deal with them. Exceptions are thrown at run time and caught in IO, much like in Java or Python.

A good rule of thumb: use values for failures that callers are expected to handle, and exceptions for the truly exceptional, such as a missing file, a dead network connection or a programming bug. Real Haskell is read-only on this site; the runnable blocks are JavaScript stand-ins for the same patterns.

error and partial functions

The simplest way to fail is error:

HASKELL
error :: String -> a

safeRoot :: Double -> Double
safeRoot x
  | x < 0     = error "negative input"
  | otherwise = sqrt x

Its result type is a, so it fits anywhere, and evaluating it throws an ErrorCall exception. That also makes error a hidden failure: the type Double -> Double promises a result for every input. Functions like head, fromJust and (!!) do the same, which is why Maybe and Either recommends total alternatives. Reserve error for "this can never happen" situations; it is a bug report, not a way to report bad input.

Errors as values

The best handling is the kind the type system checks:

HASKELL
data ParseError = Empty | NotANumber String
  deriving Show

parseAge :: String -> Either ParseError Int
parseAge "" = Left Empty
parseAge s = case reads s of
  [(n, "")] -> Right n
  _         -> Left (NotANumber s)

Callers use either, pattern matching or monadic chaining. In a do block for Either, the first Left stops everything and becomes the result:

HASKELL
total :: String -> String -> Either ParseError Int
total a b = do
  x <- parseAge a
  y <- parseAge b
  pure (x + y)

Pick the right tool

Maybe Absence, no reason needed.
Either Failure with details.
Exception Rare, unexpected, in IO.
ExceptT Either, stacked on IO.

Values for expected failures, exceptions for the rest.

1 / 2
JS Either as an error channel

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Throwing and catching in IO

Exceptions live in Control.Exception. Throw with throwIO inside IO code, and catch with catch, handle or try:

HASKELL
import Control.Exception
import System.IO.Error (isDoesNotExistError)

readConfig :: FilePath -> IO String
readConfig path = readFile path `catch` handler
  where
    handler :: IOException -> IO String
    handler e
      | isDoesNotExistError e = pure "default-config"
      | otherwise             = throwIO e

The handler's argument type decides which exceptions it catches. Here only IOException is caught; anything else passes through. Re-throw what you do not understand, as the otherwise branch does.

try turns an exception into an Either, which fits nicely with the style above:

HASKELL
result <- try (readFile "a.txt") :: IO (Either IOException String)
case result of
  Left err   -> putStrLn ("failed: " ++ show err)
  Right text -> putStr text

Catching SomeException catches everything, including "stop the program" signals, so use it only at the outermost level (to log and exit), never as a lazy catch-all in the middle of your code.

Laziness and exceptions

Exceptions fire when a value is evaluated, not when it is created. This surprises people:

HASKELL
r <- try (pure (1 `div` 0)) :: IO (Either ArithException Int)
-- r is Right <thunk>; the divide-by-zero happens later, outside the try

r2 <- try (evaluate (1 `div` 0)) :: IO (Either ArithException Int)
-- r2 is Left divide by zero

evaluate forces a value to weak head normal form inside IO, so try sees the failure. This is the same laziness that lets you build infinite lists, applied to errors. For fully evaluated results of large structures, Control.DeepSeq helps.

Cleaning up: bracket and finally

When you acquire something (a file, a lock, a connection), release it even if the code in between fails. bracket takes three actions:

HASKELL
bracket
  (openFile "out.txt" WriteMode)   -- acquire
  hClose                           -- release (always runs)
  (\h -> hPutStrLn h "data")       -- use

finally :: IO a -> IO b -> IO a runs a cleanup action after the first one, whether it finishes or throws. withFile, from the files lesson, is just bracket with the file functions filled in.

Custom exceptions

Any type with an Exception instance can be thrown. The instance is usually empty because the defaults suffice, and Show is required:

HASKELL
data BankError
  = InsufficientFunds Int
  | UnknownAccount String
  deriving Show

instance Exception BankError

withdraw :: Int -> Int -> IO Int
withdraw balance amount
  | amount > balance = throwIO (InsufficientFunds (amount - balance))
  | otherwise        = pure (balance - amount)

main :: IO ()
main = do
  r <- try (withdraw 50 80)
  case r of
    Left (InsufficientFunds missing) -> putStrLn ("short by " ++ show missing)
    Left other                       -> putStrLn ("other: " ++ show other)
    Right newBalance                 -> print newBalance

Notice that r's type is inferred from the patterns: Either BankError Int. Define a type per library or subsystem and keep its constructors descriptive.

Prefer throwIO to throw in IO code. throw can be used in pure code but is raised at an unpredictable moment, depending on when the value is forced.

ExceptT: values, stacked on IO

Real programs combine IO with typed failure. ExceptT from the transformers lesson wraps IO so that a do block can both do effects and stop at the first typed error:

HASKELL
import Control.Monad.Except
import Control.Monad.IO.Class (liftIO)

loadUser :: Int -> ExceptT String IO String
loadUser 1 = pure "ada"
loadUser n = throwError ("no user " ++ show n)

program :: ExceptT String IO ()
program = do
  a <- loadUser 1
  liftIO (putStrLn ("loaded " ++ a))
  b <- loadUser 2
  liftIO (putStrLn ("loaded " ++ b))   -- never runs

-- runExceptT program :: IO (Either String ())

The advantage over exceptions is that the error type shows in the signature, and callers must unwrap the Either to continue.

JS bracket and catch (a stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which is the best way to report an input that callers are expected to get wrong, such as a malformed age?

    An Either puts the possibility of failure in the type, so callers must handle it.
  2. 2. Why does wrapping a lazy value in try (pure x), where x divides by zero, fail to catch the error?

    Exceptions are raised when the value is evaluated. evaluate forces it within IO so try can see it.
  3. 3. What does bracket acquire release use guarantee?

    release is run when use finishes normally or with an exception, so resources are never leaked.
  4. 4. What does a handler \(e :: IOException) -> ... catch?

    The exception type in the handler selects what is caught; other exceptions propagate.

Summary

  • Use Maybe and Either (and ExceptT with IO) for failures callers should handle; they are checked by the type system.
  • error and partial functions are hidden failures; reserve them for bugs.
  • throwIO, catch, handle and try work in IO; the handler's type chooses what is caught.
  • Exceptions fire at evaluation time, so use evaluate to force a value inside try.
  • bracket and finally guarantee cleanup; define custom exceptions with instance Exception.

Next, we look at the few places where mutable state is the right tool: Mutable State: IORef, MVar and ST.