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
- Flow Operators: map, filter, transform, and take
- catch and onCompletion: Error Handling in Flow
- combine and zip: Merging Multiple Flows
- flowOn and buffer: Context and Backpressure