liveBook · Manning

Catch

As explained in Learn Haskell by Example

catches is a Haskell exception-handling function that applies multiple exception handlers to a computation.

catch handles a selected exception raised by an IO computation and runs a handler that receives the exception. Its type is Exception e => IO a -> (e -> IO a) -> IO a, so the handler catches only the exception type it declares. section 14.4

Catch a custom exception

Define SomeFailure with an Exception instance, then write `throw (SomeFailure "Whoops") `catch` \(SomeFailure s) -> putStrLn ("Caught " ++ s)`. The handler catches SomeFailure, but not exceptions from error or undefined. section 14.4

Use catch with these boundaries in mind:

  • Catch all exceptions by handling SomeException, but avoid this broad boundary when interruptions or asynchronous control flow must remain distinguishable. section 14.4
  • Use catches instead of chaining several catch applications when multiple exception types share a computation, because later handlers could catch exceptions thrown by earlier handlers. section 14.4 section 14.5
  • Use try when the safer result is an Either value containing either the exception or the computation result. section 14.5
ghci> :t catch
catch :: Exception e => IO a -> (e -> IO a) -> IO a
ghci> throw (SomeFailure "Whoops") `catch` \(SomeFailure s)
 -> putStrLn ("Caught " ++ s)
Caught Whoops

Inspect catch's type and run a minimal SomeFailure handler interactively. section 14.4

How Learn Haskell by Example covers it

How deep it goes
Explains the handler type, selective matching, broad SomeException handling, and why catches is preferred for multiple handlers.
Examples
Demonstrates SomeFailure, throw, error, undefined, and a GHCi handler that prints a caught message.
What it assumes
Assumes IO computations and exception types, while demonstrating custom Exception instances with DeriveAnyClass.
What you can do after
Apply it via Control.Exception.catch to handle a known exception type without intercepting unrelated exceptions.
How it connects
Connects catch with IO, the Exception type class, SomeException, try, catches, and asynchronous exceptions.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Haskell by Example. The section links point to the parts of the book it draws on.