Skip to content
Tutorials Center
My learning

Topics

Lesson 99 of 134 ยท Coroutines

Exceptions in Coroutines

How exceptions travel through Kotlin coroutines - launch vs async, where try/catch works, CoroutineExceptionHandler, supervisorScope, SupervisorJob and common traps, with runnable examples and real error output.

Exceptions in ordinary code are simple: they travel up the call stack until a catch handles them. In coroutines the "stack" is a tree of jobs, and the code of a child may run long after the code that started it has moved on. So the rules are different, and the old habit of wrapping a call in try/catch stops working in some places. Once you know the two rules below, the behavior is predictable.

Rule 1: a failing child cancels its parent, and through it all its siblings (unless a supervisor sits in between). Rule 2: how the exception is finally delivered depends on the builder: launch reports it to the nearest handler or crashes, async stores it and throws it when you call await(). This lesson builds on structured concurrency and cancellation, and uses the exceptions of plain Kotlin.

try/catch inside the coroutine

The simplest case works as you expect: catch inside the coroutine, around the code that can fail, and the coroutine continues normally.

Kotlin try/catch inside a coroutine

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The exception was handled where it happened, so the job completed normally. Everything in the rest of the lesson is about what happens when the exception is not caught inside.

try/catch around launch does not work

launch starts a coroutine and returns immediately. The coroutine runs later, so by the time it throws, execution has long left your try block. The exception goes up the job tree, not up your call stack.

Kotlin try/catch around launch (fails on purpose)

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

after launch is printed first, then the program crashes with Exception in thread "main" java.lang.IllegalStateException: boom. The catch never ran because launch itself returned without error. The fix is to put the try/catch inside the lambda, or around something that actually waits, such as a coroutineScope { ... } block or an await().

Wrapping scope.launch { ... } in try/catch is a classic mistake. It compiles, looks right, and never catches anything.

async: the exception waits for await

async does not report its exception to the world. It keeps it inside the Deferred, and throws it from await(). So with async you can use a normal try/catch around await():

Kotlin Catching at await

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

We used supervisorScope on purpose. Without it, the failing async would not only keep its exception for await(), it would also cancel its parent immediately (Rule 1), and the scope would fail regardless of your catch. See this trap in action:

Kotlin async still cancels its parent

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The exception is seen twice: once at await() and again as the failure of the scope itself. coroutineScope rethrows the exception of its failed child no matter what you did with it. If you want the failure to stay local, use supervisorScope, or catch inside the async block.

CoroutineExceptionHandler: the last resort

For exceptions nobody catches, a coroutine context may contain a CoroutineExceptionHandler. It is called for exceptions from launch-style coroutines, and it is meant for logging or reporting, not for recovering. By then the coroutine is already gone.

Two rules decide whether the handler is used:

  1. It must be installed on a root coroutine (one created directly in a scope, with no parent coroutine) or on the scope itself. A handler on a child launched inside another coroutine is ignored, because the child passes the exception to its parent.
  2. It does nothing for async, whose exceptions are delivered by await().
Kotlin A handler on a root coroutine

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The handler printed the failure, the job ended as cancelled, and because the scope uses a SupervisorJob it is still alive for new work. Now the common mistake, installing the handler on a child:

Kotlin A handler on a child is ignored (fails on purpose)

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The program crashes with the exception instead of calling the handler. The launch is a child of runBlocking, so its failure goes to the parent, and the parent has no handler. Put the handler on the root, for instance on a scope you create, or runBlocking(handler).

Supervisors: stopping the upward flow

A normal Job cancels the parent when a child fails. A supervisor does not: the failing child is cancelled alone, siblings continue.

  • supervisorScope { ... } is the block form, for children you start inside one function.
  • SupervisorJob() goes into a CoroutineScope(...) for a long-lived scope such as a service.

Two details trip people up. First, a SupervisorJob only protects its direct children. A grandchild's failure goes to its parent, which is then a normal child that fails. Second, you must not pass a SupervisorJob() as an argument to launch, as in launch(SupervisorJob()) { ... }; that replaces the parent link and the parent no longer waits for the child.

Kotlin Independent workers in a supervisorScope

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

In a supervisorScope, a child launched directly inside is effectively a root as far as the handler goes, so installing the handler on it works. Worker B was not disturbed.

Several exceptions at once

When more than one child fails, only the first exception is the "main" one; the others are attached to it as suppressed exceptions, so no failure is lost.

Kotlin Suppressed exceptions

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The first failure becomes the thrown exception, and the failure thrown from the finally of the cancelled sibling is attached to it. When you log errors from coroutine scopes, print the suppressed ones too, or simply log the whole stack trace.

Cancellation is not a failure

CancellationException is special: it is treated as the normal way to stop. A coroutine that ends with it does not cancel its parent, the handler is not called, and nothing is reported. That is why swallowing it is dangerous (the coroutine looks alive) and why catch (e: Exception) or runCatching around suspending code can break cancellation:

Kotlin runCatching swallows cancellation

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The cancellation was captured into a Result, and although isActive is already false, the code ran on until the next suspension point (yield), where the cancelled job finally stopped. For code that suspends, either catch specific exception types, or rethrow CancellationException:

Kotlin
// read-only example: a safe wrapper for suspending calls
inline fun <T> runCatchingSuspend(block: () -> T): Result<T> =
    try {
        Result.success(block())
    } catch (e: CancellationException) {
        throw e
    } catch (e: Exception) {
        Result.failure(e)
    }

Which tool for which situation

Situation Tool
An operation can fail and you can recover try/catch inside the coroutine
You use async and want the error as a value try/catch around await(), inside a supervisorScope or with the catch inside the block
Independent children in one function supervisorScope
A long-lived scope in a class CoroutineScope(SupervisorJob() + handler)
Report crashes of fire-and-forget work CoroutineExceptionHandler on the root
A suspending call inside runCatching catch specific types, or rethrow CancellationException

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does try { launch { throw Exception() } } catch (e: Exception) { } not catch the exception?

    The coroutine runs after launch has returned, so the exception does not pass through your try block. Catch inside the coroutine.
  2. 2. Where does the exception of an async coroutine appear?

    async stores the exception and rethrows it from await(); within a normal scope it also propagates to the parent.
  3. 3. A CoroutineExceptionHandler is installed on a launch that is a child of another launch. What happens when the child fails?

    Handlers only take effect on root coroutines (or the scope). A child hands its exception to its parent.
  4. 4. What is the main difference between coroutineScope and supervisorScope?

    supervisorScope stops the upward propagation of child failures, so each child fails independently.
  5. 5. Why is runCatching { delay(1000) } risky inside a coroutine?

    runCatching catches every Throwable, including CancellationException, and the cancellation signal gets lost unless you rethrow it.

Summary

  • A child's failure cancels its parent and siblings; supervisors (supervisorScope, SupervisorJob) stop that.
  • launch reports uncaught exceptions to a handler or crashes; async throws at await().
  • try/catch around launch catches nothing; catch inside the coroutine.
  • CoroutineExceptionHandler works only on root coroutines, is for reporting, and is ignored by async.
  • Additional failures are attached as suppressed exceptions.
  • CancellationException is not a failure; never swallow it.

Next: Channels