Bird
Raised Fist0
Kotlinprogramming~10 mins

Flow exception handling in Kotlin - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Flow exception handling
Start Flow
↓
Emit values
↓
Exception occurs?
No→Collect values
Yes↓
Catch exception
↓
Handle exception
↓
Continue or Stop Flow
↓
End
This flow shows how values are emitted, exceptions are caught and handled, then the flow continues or stops.
Execution Sample
Kotlin
flow {
  emit(1)
  emit(2)
  throw RuntimeException("Error!")
  emit(3)
}.catch { e ->
  emit(-1)
}.collect { value ->
  println(value)
}
This code emits values in a flow, throws an exception, catches it to emit -1, and collects values to print.
Execution Table
StepActionEvaluationResultOutput
1Emit 1No exceptionValue 1 emitted1
2Emit 2No exceptionValue 2 emitted2
3Throw RuntimeExceptionException thrownException caught by catch
4Emit -1 in catchHandling exceptionValue -1 emitted-1
5Emit 3 after exceptionNot reachedNo emission
6Collect valuesAll emitted values collectedPrinted 1, 2, -11 2 -1
💡 Exception thrown at step 3, caught and handled; flow does not emit 3 after exception.
Variable Tracker
VariableStartAfter 1After 2After 3After 4Final
emittedValuenone12exception-1-1
exceptionCaughtfalsefalsefalsetruetruetrue
Key Moments - 3 Insights
Why is the value 3 never emitted after the exception?
Because the exception interrupts the flow at step 3, so the code after the throw is not executed (see execution_table step 5).
How does the catch block emit a value after an exception?
The catch block handles the exception and can emit new values, like -1 at step 4, continuing the flow safely.
Does the flow stop completely after an exception?
Not necessarily; if the exception is caught and handled, the flow can continue emitting values or complete gracefully.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output at step 2?
A3
B-1
C2
DException
💡 Hint
Check the 'Output' column for step 2 in the execution_table.
At which step does the exception get caught?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
Look at the 'Action' and 'Result' columns around steps 3 and 4.
If the catch block did not emit -1, what would be the collected output?
A1, 2
B1, 2, -1
C1, 2, 3
DNo output
💡 Hint
Refer to the variable_tracker and execution_table showing emitted values and catch behavior.
Concept Snapshot
Kotlin Flow exception handling:
- Use .catch { e -> } to handle exceptions in a flow.
- Exceptions stop normal emission; catch can emit fallback values.
- Flow continues after catch if handled.
- Use collect { } to receive emitted values.
- Exception interrupts flow unless caught.
Full Transcript
This visual execution shows how Kotlin Flow handles exceptions. The flow emits values 1 and 2 normally. At step 3, a RuntimeException is thrown, interrupting the flow. The catch block catches this exception and emits -1 as a fallback value. The flow does not emit the value 3 after the exception because the throw stops normal execution. The collected output prints 1, 2, and -1. Variables track emitted values and whether an exception was caught. Key moments clarify why emission stops after an exception and how catch allows continuation. The quiz tests understanding of output at each step and the role of catch. The snapshot summarizes the syntax and behavior of flow exception handling in Kotlin.

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

  1. 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.
  2. Step 2: Differentiate from other operators

    Operators like map transform values, collect starts the flow, and cancel stops it. Only catch handles errors.
  3. Final Answer:

    To handle exceptions that occur during the flow emission -> Option B
  4. 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

  1. Step 1: Recall the correct operator name

    The operator to handle exceptions in Kotlin Flow is catch, not try, handle, or error.
  2. 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) }.
  3. Final Answer:

    flow.catch { e -> emit(fallbackValue) } -> Option A
  4. Quick Check:

    Correct catch syntax = flow.catch { e -> ... } [OK]
Hint: Use catch, not try, for Flow exceptions [OK]
Common Mistakes:
  • Using try instead of catch
  • Wrong operator names like handle or error
  • Incorrect lambda parameter usage
3. What will be the output of the following Kotlin code?
import kotlinx.coroutines.flow.*
suspend fun main() {
    flow {
        emit(1)
        throw RuntimeException("Error!")
    }
    .catch { emit(99) }
    .collect { println(it) }
}
medium
A. 1 Error!
B. Only 99
C. Error! Exception thrown
D. 1 99

Solution

  1. Step 1: Analyze the flow emissions and exception

    The flow emits 1, then throws a RuntimeException. The catch operator catches this exception and emits 99 as a fallback.
  2. Step 2: Understand the collection output

    The collector prints each emitted value. So it prints 1 first, then after catching the exception, it prints 99.
  3. Final Answer:

    1 99 -> Option D
  4. Quick Check:

    Emit before error + catch fallback = 1 and 99 [OK]
Hint: catch emits fallback after error, original emits stay [OK]
Common Mistakes:
  • Expecting exception message to print
  • Thinking flow stops without catch
  • Ignoring emitted values before error
4. Identify the error in this Kotlin Flow exception handling code:
flow {
    emit(10)
    throw IllegalStateException("Oops")
}.catch { e ->
    println("Caught: $e")
}.collect {
    println(it)
}
medium
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

  1. 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.
  2. 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.
  3. Final Answer:

    Missing emit inside catch to provide fallback value -> Option A
  4. 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

  1. 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.
  2. 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.
  3. Final Answer:

    flow { for (i in 1..3) { if (i == 2) throw Exception() emit(i) } }.catch { emit(-1) } -> Option C
  4. 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]
Hint: Throw inside flow, catch emits fallback -1 [OK]
Common Mistakes:
  • Not throwing exception inside emission loop
  • Rethrowing exception in catch instead of emitting fallback
  • Throwing exception outside emission range
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard