liveBook · Manning

MonadThrow

As explained in Functional Programming in Scala, Second Edition

MonadThrow is a type class extending Monad with operations for raising errors and handling them later.

MonadThrow extends Monad with operations for raising errors and handling them later. It makes failures explicit within effectful computations instead of leaving error handling outside the computation. section 15.3.2

trait MonadThrow[F[_]] extends Monad[F]:
  extension [A](fa: F[A])
    def attempt: F[Try[A]]
    def handleErrorWith(h: Throwable => F[A]): F[A] =
      attempt.flatMap:
        case Failure(t) => h(t)
        case Success(a) => unit(a)
 
  def raiseError[A](t: Throwable): F[A]

The interface combines attempt, handleErrorWith, and raiseError: computations can expose failures, recover from them, or create them explicitly. section 15.3.2

Handling a failed computation

A Task that evaluates "asdf".toInt can be transformed with map, inspected using attempt, or recovered with handleErrorWith(_ => Task(0)). In stream processing, MonadThrow lets step interpret Pull handlers and lets Stream operations raise and handle errors. section 15.3.2

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Defines three operations and applies them while stepping Pull, including nested-handler rewriting; defers formal laws to an exercise.
Examples
Demonstrates Task parsing, Stream failures, Pull handlers, and file release through onComplete.
What it assumes
Assumes Monad and introduces error handling as an additional capability for arbitrary effects.
What you can do after
Apply it via MonadThrow to raise, inspect, and handle errors in effectful stream processing.
How it connects
Connects Monad with error handling, Stream, Pull, attempt, and resource cleanup.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Programming in Scala, Second Edition. The section links point to the parts of the book it draws on.