Recall & Review
beginner
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, -1Click to reveal answer
Which operator in Kotlin Flow is used to handle exceptions?
✗ 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?
✗ 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?✗ 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?✗ 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?
✗ 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.