CodeGym /Courses /Kotlin SELF /Errors and cancellation in Channel and Flow: cleanup an...

Errors and cancellation in Channel and Flow: cleanup and exception handling

Kotlin SELF
Level 54, Lesson 4
Available

1. Introduction

If you previously wrote only sequential code, an exception there often feels like an “unpleasant surprise”. In coroutines it is more like rain: unpleasant, but if you live in a city, an umbrella should be nearby. Plus you get “cancellation”: we intentionally tell a coroutine “stop, no need to continue”—and that is a normal scenario, not a crash.

In coroutine systems, an important idea is this: Channel and Flow are not just APIs, they are mini-protocols. A protocol has completion rules, places where an error must become visible, and a place where cleanup must happen. If you forget these three things, you get two classic “beginner symptoms”: the program hangs “forever”, or the program crashes “somewhere over there”, and you cannot understand why.

To ground the idea, let’s very briefly recall the difference: Channel delivers each message to exactly one receiver, while Flow produces values only when it is collected (collect). This difference directly affects where and how errors surface and what correct completion looks like.

2. Channel: completion, errors, and cleanup

Where errors “live”, and why hanging is also an error

When you work with a Channel, you almost always have two roles: someone sends (send), someone receives (receive or for (x in ch)). And both operations are suspend, meaning they can wait. That is exactly why a channel is the champion of hangs: if nobody sends a value and the channel is not closed, receive() will wait. And it will wait for a long time. Sometimes for the entire lifetime of your program, which is dramatic and mildly annoying.

Errors with channels can be “regular” (your error("boom"), IllegalStateException, division by zero, etc.), and they can be protocol-related: trying to send to a closed channel or trying to receive from a closed channel via receive(). Protocol errors are especially tricky because they often show up “not where” you expected the problem to be.

Let’s start with a small example that shows: if you close a channel and then try to send, that is already an exception, not “Kotlin will figure it out”.

import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.channels.Channel

fun main() = runBlocking {
    val ch = Channel<Int>()
    ch.close()

    try {
        ch.send(1)
    } catch (e: Throwable) {
        println("Send failed: ${e::class.simpleName}") // ClosedSendChannelException (roughly)
    }
}

What matters here is not the exact exception class (it can vary in details across different kotlinx.coroutines versions), but the meaning: “closed” means the protocol said “there will be no more values”, and you cannot send anymore.

Now the second point: reading. If you call receive() on a closed channel, you also get an exception. That is why consumers more often use the for (x in ch) loop, because it finishes normally when the channel is closed and elements are exhausted—without an exception.

import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.launch

fun main() = runBlocking {
    val ch = Channel<Int>()

    launch {
        ch.send(10)
        ch.close()
    }

    for (x in ch) {
        println("x=$x") // x=10
    }
    println("done")     // done
}

That done is your happy ending: the consumer did not hang, did not crash, and did not start a drama.

Cleanup via try/finally: so consumers do not hang

When people say “do cleanup”, it sounds like advice from neat people who also do morning exercises. In practice it is a harsh necessity: if the producer finishes for some reason (error, cancellation, early return) and the channel is not closed, the consumer can hang forever. And here is the interesting part: a hang is also an error, just without a stack trace, which makes it especially annoying.

A rule worth learning like the multiplication table: if a coroutine “owns” producing values, then closing the channel should usually be nearby and often—in finally. This is not magic; it is how you guarantee protocol completion.

import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.launch

fun main() = runBlocking {
    val ch = Channel<Int>()

    val producer = launch {
        try {
            repeat(3) { i ->
                ch.send(i)
            }
        } finally {
            ch.close()
        }
    }

    for (x in ch) {
        println("got $x") // got 0 / got 1 / got 2
    }

    producer.join()
}

Meaning: even if something goes wrong inside repeat, the finally block runs, the channel closes, and the consumer exits the loop.

And here a grown-up thought appears: close() is not “resource cleanup” in the style of file.close(). It is a protocol signal: “there will be no more values”. You can close a channel without an error—simply because the work is done.

Coroutine cancellation and CancellationException: why you must not “accidentally swallow” it

In previous days on structured concurrency, you have already seen that coroutines are canceled via Job.cancel() and usually awaited via cancelAndJoin(). Cancellation is a normal scenario. For example, you started processing, the user changed their mind (in UI), or you hit a timeout (we will not dive into timeouts today, but the idea is similar).

The key point: cancellation often manifests as an exception of type CancellationException. It is used as a “cancellation delivery mechanism” through suspension points (delay, receive, send, collect, etc.). That is why there is a thin line between “handle an error” and “break the cancellation mechanism”.

Let’s look at an example of canceling a consumer. Note: we do not try to “fix” cancellation; we just guarantee cleanup in finally.

import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.launch
import kotlinx.coroutines.delay
import kotlinx.coroutines.cancelAndJoin

fun main() = runBlocking {
    val ch = Channel<Int>()

    val consumer = launch {
        try {
            for (x in ch) {
                println("consume $x") // consume 0 / consume 1 ...
            }
        } finally {
            println("consumer finished") // consumer finished
        }
    }

    repeat(5) { i -> ch.send(i) }
    delay(50)
    consumer.cancelAndJoin()
    ch.close()
}

What matters here is that finally runs on cancellation. That is your “guaranteed point” where you can release resources, write logs, close your own stuff.

The most dangerous mistake in places like this is to write a broad catch (e: Throwable) and “happily” continue as if nothing happened. If you catch CancellationException and do not rethrow it, you can make cancellation “not work”, and the system will behave oddly: someone canceled it, but it keeps living.

We will not dive into the subtleties of how to filter exceptions properly right now, but the practical rule is this: if you catch Throwable, then cancellation almost always needs to be rethrown (for example, throw e), otherwise cancellation loses its meaning.

3. Flow: where to catch exceptions and how to finish collection

Where an error surfaces, and why catch is not a “shield against everything”

After channels, Flow can initially seem “simpler”: no close(), no “who closes it” protocol; the stream ends when the flow { ... } block ends. And that is true. But Flow has a different trait: an error usually “floats” to where you call collect. And if you pick the wrong place to handle it, you will stare at the stack trace and think, “But I added catch! Why did it still crash?”

Let’s be careful and honest: catch in Flow catches errors that occurred higher in the chain (upstream). That means: errors from flow { ... }, map, filter, onEach before catch. But if you throw an exception inside collect { ... }, catch will not catch it, because collect is already downstream—“after the chain”.

First, an example of “error in the source, caught by catch”:

import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect

fun main() = runBlocking {
    val f = flow {
        emit(1)
        error("boom")
    }

    f.catch { e ->
        println("caught: ${e.message}") // caught: boom
        emit(-1)
    }.collect { v ->
        println("v=$v")                 // v=1 / v=-1
    }
}

Now an example of “error inside collect”: we add catch, but it will not help, so we add an outer try/catch.

import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect

fun main() = runBlocking {
    val f = flow { emit(1) }

    try {
        f.catch { println("caught upstream") }
            .collect { _ ->
                error("fail in collect")
            }
    } catch (e: Throwable) {
        println("outer caught: ${e.message}") // outer caught: fail in collect
    }
}

This rule is useful to remember almost like a road sign: catch does not catch errors that you yourself throw in collect. And that is logical: collect is your terminal handler, not part of the pipeline.

Canceling Flow and finally around collect

Now about canceling Flow. Flow is great because it naturally “plays well” with backpressure: if processing is slow, the emitter cannot endlessly “spray” values—it will suspend at emit and other suspend points. This same mechanism also means cancellation passes naturally: cancel the collector’s Job, and collection stops.

And here you start appreciating finally even more, because collect often lives inside a separate coroutine. If it gets canceled, you still want to see the final line collector finished or close some of your own things.

import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.launch
import kotlinx.coroutines.delay
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.collect

fun main() = runBlocking {
    val f = flow {
        var i = 0
        while (true) {
            emit(i++)
            delay(50)
        }
    }

    val job = launch {
        try {
            f.collect { v ->
                println("v=$v") // v=0 / v=1 / v=2 ...
            }
        } finally {
            println("collector finished") // collector finished
        }
    }

    delay(160)
    job.cancelAndJoin()
}

What matters here is the “coroutine + try/finally” construction. It is exactly the same idea as with a channel, just instead of close() you have “stop collecting” and whatever completion actions you need.

Notice an “advanced nuance”: cancellation in coroutines is not “kill a thread”. It is cooperative cancellation: the coroutine must reach a suspend point or check its state. In our example it regularly does delay(50), so cancellation triggers quickly.

Mini example: TelemetryConsole resilient to errors and cancellation

So it does not feel like we are discussing spherical coroutines in a vacuum, let’s continue the day’s mini-app: console monitoring that prints events “as if from sensors”. Let’s call it TelemetryConsole. The idea is simple: there is an event source, there is processing, there is output. Sometimes the source breaks, sometimes the user cancels collection (in a real app this could be leaving a page or switching modes).

Let’s make two small functions: one creates an event Flow, the other starts collection with robust completion.

First, the event model (intentionally very simple, no classes and architecture—we are not focusing on that now):

data class TelemetryEvent(val id: Int, val message: String)

Now the source (it sometimes “crashes” so we can practice):

import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow

fun telemetryFlow(): Flow<TelemetryEvent> = flow {
    for (i in 1..5) {
        emit(TelemetryEvent(i, "ping"))
        delay(30)
    }
    error("sensor disconnected")
}

Now startup and error handling. Note: we use catch for upstream (the source), and try/finally around collect to guarantee cleanup on cancellation and on any exit.

import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect

fun main() = runBlocking {
    try {
        telemetryFlow()
            .catch { e ->
                println("telemetry error: ${e.message}") // telemetry error: sensor disconnected
                emit(TelemetryEvent(-1, "fallback-event"))
            }
            .collect { ev ->
                println("event=${ev.id} ${ev.message}")  // event=1 ping ...
            }
    } finally {
        println("telemetry stopped")                      // telemetry stopped
    }
}

This snippet immediately shows the “responsibility map”: the body of flow {} is responsible for generating values and can fail, catch turns a failure into understandable behavior (log + fallback value), and the outer finally guarantees the final completion point even if collection was canceled or something totally unexpected happened.

Cheat sheet: where we close, where we catch, where we do cleanup

Sometimes it is useful not only to read code, but also to keep a “map” in your head. Here is a simple cheat-sheet table (not a law, but a practical guideline):

Tool How it “ends” normally Where we most often catch errors Where we do cleanup
Channel
close() + the consumer reads for (x in ch) until the end In role coroutines (producer, worker) via try/catch Usually at the channel owner: try/finally { ch.close() }
Flow
the body of flow { ... } ends by itself Upstream via catch, downstream (in collect) via try/catch around collect try/finally around collect (and/or inside coroutine wrappers)

And an important line to remember: Channel is communication between coroutines (a queue), while Flow is a description of a value sequence that starts at collect. From that follow different completion locations and different “truth points” for errors.

4. Common mistakes

Mistake #1: the channel is not closed because “we already sent everything”.
This almost always ends with the consumer waiting for one more value that will never arrive. It is especially tricky when you tested with a small example and you always happened to “finish in time”. A reliable style is to close the channel in finally in the coroutine responsible for producing values, so completion does not depend on whether “we made it to the end”.

Mistake #2: trying to treat a channel like a broadcast to “all listeners”.
If you start two consumers on the same Channel, each message will be received by only one of them, not both. That is normal queue semantics, not a bug. Because of this mistake, people sometimes think “messages are lost”, while in reality they are distributed among receivers.

Mistake #3: adding catch in Flow and being sure it will catch absolutely everything.
catch catches errors that happened before it in the chain (upstream). An error inside collect { ... } is already downstream, so you must catch it with a regular try/catch around collect. Otherwise you will be surprised why “but there is catch, and it still crashed”.

Mistake #4: writing catch (Throwable) and swallowing cancellation.
Coroutine cancellation often shows up as CancellationException. If you catch all exceptions and do not rethrow cancellation, you break structured concurrency: the parent said “stop”, and the child pretended it did not hear. Even if you are not yet ready for “perfectly correct” exception filtering, keep the principle in mind: cancellation is not an error; you usually do not “fix” it—you respect it.

Mistake #5: doing cleanup “after the loop”, but not in finally.
In asynchronous code, “after the loop” might never happen: cancellation, exception, early return—and your cleanup did not run. That is why finally is not decoration; it is how you guarantee behavior. In coroutines it is especially important because stopping often occurs at a suspend point and looks like an exception.

Mistake #6: confusing “protocol completion” with “just exiting the function”.
With Channel, leaving the producer function is not enough. If you did not close the channel, the consumer will not learn that “there will be no more values”. With Flow, it is the opposite: the body of flow {} ends—so the flow is complete, and there is no additional close(), and none is needed. When these models get mixed up in your head, you get extra close() calls in the wrong places and hangs “for no clear reason”.

1
Task
Kotlin SELF, level 54, lesson 4
Locked
Graceful finish
Graceful finish
1
Task
Kotlin SELF, level 54, lesson 4
Locked
Forbidden send
Forbidden send
1
Task
Kotlin SELF, level 54, lesson 4
Locked
Subscriber cancellation
Subscriber cancellation
1
Task
Kotlin SELF, level 54, lesson 4
Locked
Source failure
Source failure
1
Survey/quiz
`Channel` and `Flow`, level 54, lesson 4
Unavailable
`Channel` and `Flow`
`Channel` and `Flow`
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION