0
0
Kotlinprogramming~5 mins

Flow exception handling in Kotlin

Choose your learning style9 modes available
Introduction

Flow exception handling helps you catch and manage errors when working with streams of data. It keeps your program running smoothly without crashing.

When you want to handle errors while collecting data from a Flow.
When you need to provide fallback values if something goes wrong in the data stream.
When you want to log or show error messages during data processing.
When you want to clean up resources or perform actions after an error occurs in a Flow.
Syntax
Kotlin
flow {
    // emit values
}.catch { e ->
    // handle exception e
}.collect { value ->
    // process value
}

The catch operator catches exceptions inside the Flow before they reach collect.

Use emit inside flow { } to send values.

Examples
This example emits 1, then throws an error. The catch prints the error message.
Kotlin
flow {
    emit(1)
    throw RuntimeException("Oops")
}.catch { e ->
    println("Caught: ${e.message}")
}.collect { value ->
    println(value)
}
This example throws an error when value is 2, then catch emits a fallback value -1.
Kotlin
flowOf(1, 2, 3).map {
    if (it == 2) throw IllegalStateException("No 2 allowed")
    else it
}.catch { e ->
    emit(-1) // fallback value
}.collect { println(it) }
Sample Program

This program creates a flow that emits two numbers, then throws an exception. The catch block catches the exception, prints a message, and emits a fallback value 0. The collect prints all received values.

Kotlin
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
    val numbers = flow {
        emit(10)
        emit(20)
        throw Exception("Error in flow")
        emit(30) // won't be reached
    }

    numbers
        .catch { e ->
            println("Caught exception: ${e.message}")
            emit(0) // fallback value
        }
        .collect { value ->
            println("Received: $value")
        }
}
OutputSuccess
Important Notes

The catch operator only catches exceptions from upstream flow operators, not from collect.

Use onCompletion to run code after flow finishes or errors.

Summary

Use catch to handle errors inside a Flow.

You can emit fallback values inside catch.

Exception handling keeps your data stream safe and your app stable.