What is the purpose of exception handling in Kotlin Flow?
Exception handling in Kotlin Flow is used to catch and manage errors that occur during the flow's emission or collection, preventing crashes and allowing graceful recovery.
Click to reveal answer
beginner
Which operator is commonly used to catch exceptions in a Kotlin Flow?
The catch operator is used to catch exceptions emitted by the upstream flow and handle them, such as logging or emitting fallback values.
Click to reveal answer
intermediate
How does the catch operator work in Kotlin Flow?
The catch operator intercepts exceptions from upstream flows. Inside its block, you can handle the exception or emit alternative values to continue the flow.
Click to reveal answer
beginner
What happens if an exception is not caught in a Kotlin Flow?
If an exception is not caught, it will cancel the flow collection and propagate the error to the caller, potentially crashing the app or stopping the flow.
Click to reveal answer
intermediate
Show a simple Kotlin Flow example that emits numbers and handles exceptions using catch.
```kotlin
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.runBlocking
fun simpleFlow(): Flow<Int> = flow {
emit(1)
emit(2)
throw RuntimeException("Oops!")
}
fun main() = runBlocking {
simpleFlow()
.catch { e -> emit(-1) } // Emit -1 on error
.collect { value -> println(value) }
}
```
This prints: 1, 2, -1
Click to reveal answer
Which operator in Kotlin Flow is used to handle exceptions?
Acatch
Bmap
Cfilter
Dcollect
✗ Incorrect
The catch operator is specifically designed to catch exceptions in a flow.
What happens if an exception occurs in a flow and is not caught?
AThe exception is ignored
BThe flow continues normally
CThe flow is cancelled and the exception propagates
DThe flow retries automatically
✗ Incorrect
Uncaught exceptions cancel the flow and propagate the error to the caller.
In the catch operator, what can you do with the caught exception?
AOnly log it
BIgnore it silently
CConvert it to a different exception automatically
DEmit alternative values or rethrow
✗ Incorrect
Inside catch, you can emit fallback values or rethrow the exception.
Where should the catch operator be placed in a flow chain to catch exceptions from upstream?
AAfter the operators that might throw exceptions
BBefore any operators
CAt the very end after <code>collect</code>
DIt does not matter
✗ Incorrect
catch should be placed after operators that might throw exceptions to catch them.
Which of these is NOT a valid way to handle exceptions in Kotlin Flow?
AUsing <code>catch</code> operator
BIgnoring exceptions silently
CUsing try-catch inside <code>flow</code> builder
DUsing <code>retry</code> operator to retry on failure
✗ Incorrect
Ignoring exceptions silently is not a good practice and not a valid handling method.
Explain how exception handling works in Kotlin Flow and why it is important.
Think about how errors can stop a flow and how catch helps.
You got /4 concepts.
Describe a simple example of using the catch operator in a Kotlin Flow to handle an error.
Imagine a flow that emits numbers but throws an error in the middle.
You got /5 concepts.
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]