Exceptions

Exceptions are for IO

The course has used Maybe and Either for failures that a caller can handle. Some failures are not like that: a missing file, a broken pipe, a division by zero that a program did not expect. Those are exceptions, they live in IO, and Control.Exception is the module that catches them.

try :: Exception e => IO a -> IO (Either e a) catch :: Exception e => IO a -> (e -> IO a) -> IO a throwIO :: Exception e => e -> IO a evaluate :: a -> IO a

The type Exception e is a class: an exception is a value of a type with an instance, and the common ones such as IOException and ArithException come from the standard library. try turns an action into an action that returns Either e a, which is the bridge back to the Either of the last lessons.

try and catch

A division by zero and a missing file, both caught and both turned into a value:

module Main (main) where import Control.Exception (ArithException, IOException, evaluate, try) main :: IO () main = do number <- try (evaluate (1 `div` 0)) :: IO (Either ArithException Int) print number missing <- try (readFile "/tmp/no-such-file-here.txt") :: IO (Either IOException String) print (either (const "missing file") (const "read the file") missing)

ghc -Wall -O1 -o exceptions exceptions.hs
./exceptions

Left divide by zero
"missing file"

The annotation on try chooses which exception type to catch, and the compiler needs it because the same expression could catch many types. The first line prints the exception value, which has a Show instance with the message the runtime would have printed. The second replaces the whole exception with a fixed string, which is what a program that only needs to know whether the file was readable does.

evaluate and lazy values

A lazy value can throw when it is forced, which is not necessarily where it was built. try (return (1 `div` 0)) catches nothing, because return wraps an unevaluated expression; evaluate forces it to weak head normal form inside the action, so the exception happens where try can see it.

try (return (1 `div` 0)) :: IO (Either ArithException Int) -- Right _ try (evaluate (1 `div` 0)) :: IO (Either ArithException Int) -- Left divide by zero

That is the single most common surprise with exceptions in Haskell: the exception is raised by the consumer, not by the producer, unless something forces the value. A strict field, seq, evaluate or a strict fold moves the evaluation to a place the program controls.

bracket closes the resource

A resource that must be released is the job of bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c: acquire, use, release, with the release guaranteed even if the use throws. The file handles of the last lesson use it under another name.

module Main (main) where import Control.Exception (bracket) main :: IO () main = bracket open close use where open = putStrLn "open the resource" close _ = putStrLn "close the resource" use _ = putStrLn "use the resource"

ghc -Wall -O1 -o bracket bracket.hs
./bracket

open the resource
use the resource
close the resource

The order is the guarantee: the close runs after the use whatever the use does. bracket_ is the same without a value to pass, and finally attaches an action to one side only. A manual openFile followed by a hClose is the same contract written by hand and broken by the first exception.

The course position: model expected failures with Maybe or Either, catch exceptions only at the edge of the program, and never use error for a condition a caller could handle. error is for a programmer mistake, and throwIO is for an IO failure that the type does not carry.

Exercises

  1. Catch the exception of head [] with try and evaluate, and print the result.
  2. Write a function that tries to read a file and returns Either String String with the message on failure.
  3. Show the difference between try (return (1 `div` 0)) and the evaluate version.
  4. Use bracket to print three lines in the right order with a nested action.
  5. Replace error "bad input" in a function with an Either result and explain the change for the caller.
  6. Explain why the annotation on try is required.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What is the type of try?

    Answer

    Exception e => IO a -> IO (Either e a)

    try runs the action and turns a thrown exception into a Left value.

  2. What does evaluate do?

    Answer

    Forces a value to weak head normal form inside an IO action

    It makes the evaluation happen where the action can catch the exception.

  3. Why can try (return (1 div 0)) return Right?

    Answer

    The division is not evaluated, so no exception is raised yet

    The expression stays a thunk inside the action, so the exception would fire later, outside try.

  4. What does bracket open close use guarantee?

    Answer

    close runs even if use throws

    bracket is the acquire-use-release pattern with the release guaranteed.

  5. What does this program print? ``module Main (main) where import Control.Exception (ArithException, evaluate, try) main :: IO () main = do r <- try (evaluate (1 div 0)) :: IO (Either ArithException Int) print r``

    Answer

    Left divide by zero

    evaluate forces the division inside try, which catches the arithmetic exception as a Left.

  6. Which failure belongs in an exception rather than in Either?

    Answer

    A missing file discovered by the runtime

    IO failures such as a missing file are exceptions; expected validation belongs in the type.

  7. What does catch action handler do?

    Answer

    Runs the action and calls the handler if it throws

    catch replaces a thrown exception with the handler action.

  8. What does this program print? module Main (main) where import Control.Exception (bracket) main :: IO () main = bracket (putStrLn "open") (\_ -> putStrLn "close") (\_ -> putStrLn "use")

    Answer

    open, use, close on three lines

    bracket acquires, runs the use action and releases afterwards.

  9. Why is error a poor way to report bad user input?

    Answer

    It throws an exception the caller cannot see in the type

    The failure is invisible in the signature, so the caller cannot handle it without catching exceptions.

  10. What is the type of the second argument of try's annotation, such as ArithException?

    Answer

    An exception type with an Exception instance

    try is parameterised by the exception type it catches, which must have the instance.

The code on this page was built with GHC 9.10.3 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev