📖 Scenario: You are building a simple Kotlin program that uses a Flow to emit numbers. Sometimes, the flow might throw an exception. You want to handle this exception gracefully and provide a fallback value.
🎯 Goal: Create a Kotlin Flow that emits numbers from 1 to 5 but throws an exception at number 3. Then, handle the exception using catch to emit a fallback value of 0. Finally, collect and print all emitted values.
📋 What You'll Learn
Create a Flow that emits numbers 1 to 5
Throw an exception when the number 3 is emitted
Use catch to handle the exception and emit 0 as fallback
Collect the flow and print each emitted value
💡 Why This Matters
🌍 Real World
Flows are used in Kotlin to handle streams of data asynchronously, such as user inputs, network responses, or sensor data. Handling exceptions in flows ensures your app can recover gracefully from errors.
💼 Career
Understanding Flow exception handling is important for Kotlin developers working on Android apps or backend services that require reactive programming and robust error management.
Progress0 / 4 steps
1
Create a Flow that emits numbers 1 to 5
Create a Flow called numberFlow that emits the numbers 1, 2, 3, 4, and 5 using flow { } and emit().
Kotlin
Hint
Use flow { } to create the flow and emit() to send each number.
2
Throw an exception when emitting number 3
Modify the numberFlow so that it throws an Exception("Error at 3") when trying to emit the number 3. Emit numbers 1 and 2 normally before the exception.
Kotlin
Hint
Use throw Exception("Error at 3") right after emitting 2.
3
Handle the exception with catch and emit fallback
Use the catch operator on numberFlow to catch the exception and emit 0 as a fallback value.
Kotlin
Hint
Use .catch { e -> emit(0) } after the flow to handle exceptions.
4
Collect and print all emitted values
Collect the numberFlow using collect inside a runBlocking block and print each emitted value with println().
Kotlin
Hint
Use runBlocking to run the coroutine and numberFlow.collect { value -> println(value) } to print each emitted value.
Practice
(1/5)
1. What is the primary purpose of the catch operator in Kotlin Flow?
easy
A. To start collecting the flow
B. To handle exceptions that occur during the flow emission
C. To transform emitted values into another type
D. To cancel the flow collection
Solution
Step 1: Understand the role of catch in Flow
The catch operator is designed to intercept exceptions that happen during the emission of values in a Flow.
Step 2: Differentiate from other operators
Operators like map transform values, collect starts the flow, and cancel stops it. Only catch handles errors.
Final Answer:
To handle exceptions that occur during the flow emission -> Option B
Quick Check:
Flow error handling = catch [OK]
Hint: Remember: catch is for errors inside Flow [OK]
Common Mistakes:
Confusing catch with map or collect
Thinking catch cancels the flow
Assuming catch transforms values
2. Which of the following is the correct syntax to catch exceptions in a Kotlin Flow?
easy
A. flow.catch { e -> emit(fallbackValue) }
B. flow.try { e -> emit(fallbackValue) }
C. flow.handle { e -> emit(fallbackValue) }
D. flow.error { e -> emit(fallbackValue) }
Solution
Step 1: Recall the correct operator name
The operator to handle exceptions in Kotlin Flow is catch, not try, handle, or error.
Step 2: Verify the lambda syntax
The lambda receives the exception e and can emit fallback values inside it, matching the syntax flow.catch { e -> emit(fallbackValue) }.
Final Answer:
flow.catch { e -> emit(fallbackValue) } -> Option A
A. Missing emit inside catch to provide fallback value
B. catch block should be after collect
C. collect should be inside catch block
D. No error, code is correct
Solution
Step 1: Review catch usage
The catch block prints the exception but does not emit any fallback value, so the flow ends after the exception.
Step 2: Understand flow continuation
Without emitting a fallback value inside catch, the collector won't receive any value after the error, which might not be intended.
Final Answer:
Missing emit inside catch to provide fallback value -> Option A
Quick Check:
catch without emit = no fallback value [OK]
Hint: Emit fallback inside catch to continue flow after error [OK]
Common Mistakes:
Placing catch after collect
Trying to collect inside catch
Not emitting fallback value in catch
5. You want to create a Kotlin Flow that emits numbers 1 to 3, but if an exception occurs, it should emit -1 and then complete. Which code snippet correctly implements this behavior?
hard
A. flow {
for (i in 1..3) emit(i)
}.catch { emit(-1) }
B. flow {
for (i in 1..3) {
if (i == 4) throw Exception()
emit(i)
}
}.catch { emit(-1) }
C. flow {
for (i in 1..3) {
if (i == 2) throw Exception()
emit(i)
}
}.catch { emit(-1) }
D. flow {
for (i in 1..3) emit(i)
}.catch { throw Exception() }
Solution
Step 1: Identify where exception occurs
flow {
for (i in 1..3) {
if (i == 2) throw Exception()
emit(i)
}
}.catch { emit(-1) } throws an exception at i == 2, triggering the catch block to emit -1 as fallback.
Step 2: Confirm fallback emission and completion
The catch block emits -1, then the flow completes. Codes without throwing an exception during the emission loop do not trigger catch. Code that rethrows the exception in catch does not emit fallback.
Final Answer:
flow {
for (i in 1..3) {
if (i == 2) throw Exception()
emit(i)
}
}.catch { emit(-1) } -> Option C
Quick Check:
Throw inside flow + catch emit fallback = flow {
for (i in 1..3) {
if (i == 2) throw Exception()
emit(i)
}
}.catch { emit(-1) } [OK]