liveBook · Manning

Error propagation

As explained in Kotlin in Action, 2E

Error propagation is the transmission of an error or exception from the computation where it occurs to an enclosing or related computation.

Error propagation moves an uncaught exception from the coroutine where it occurs to its parent, making that parent responsible for handling it. section 18.1

An async exception reaches await

A coroutine created with async can throw an UnsupportedOperationException. Calling await() rethrows that exception so a surrounding try/catch can handle it, while the original failure is also observed by the parent coroutine. With launch, placing the try/catch inside the child handles the exception; placing it around launch does not. section 18.1

Listing 18.1 An async coroutine that throws an exception
import kotlinx.coroutines.*

fun main(): Unit = runBlocking {
   val myDeferredInt: Deferred<Int> = async {
       throw UnsupportedOperationException("Ouch!")
   }
   try {
       val i: Int = myDeferredInt.await()
       println(i)
   } catch (u: UnsupportedOperationException) {
       println("Handled: $u")
   }
}

Use the runnable async example to trace exception creation, await(), and handling in sequence. section 18.1

How Kotlin in Action, 2E covers it

How deep it goes
Explains child-to-parent propagation and await() rethrowing, while deferring broader parent-handling strategies.
Examples
Uses async with await(), launch with try/catch, and UnsupportedOperationException examples.
What it assumes
Assumes basic coroutine familiarity while establishing how child failures reach parents.
What you can do after
Diagnose/debug with it by locating the parent responsible for an uncaught coroutine exception and choosing where to catch it.
How it connects
Links coroutines with exceptions, parent-child relationships, async, await(), launch, runBlocking, and flows.

Also explained in

Compare how 4 books explain error propagation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.