0Pricing
Kotlin Academy · Lesson

catch and onCompletion: Error Handling in Flow

Catch upstream exceptions and react to flow completion events.

Flow Exceptions Basics

Exceptions in a flow terminate it. Without handling, the exception propagates to the collector and the flow ends.

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun main() = runBlocking {
    try {
        flow {
            emit(1)
            throw RuntimeException("stream error")
            emit(2)
        }.collect { println(it) }
    } catch (e: Exception) {
        println("Caught: ${e.message}")
    }
}

catch Operator

catch handles upstream exceptions and can emit fallback values or rethrow. It does not catch exceptions thrown by the collector itself.

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun main() = runBlocking {
    flow {
        emit(1)
        throw RuntimeException("oops")
    }.catch { e ->
        println("Caught: ${e.message}")
        emit(-1)  // fallback value
    }.collect { println(it) } // 1, then -1
}

All lessons in this course

  1. Flow Operators: map, filter, transform, and take
  2. catch and onCompletion: Error Handling in Flow
  3. combine and zip: Merging Multiple Flows
  4. flowOn and buffer: Context and Backpressure
← Back to Kotlin Academy