Cancellation and exception handling
Cancellation and Exception Handling Deep Dive¶
Overview¶
Cancellation and exception propagation are where coroutine understanding becomes production-relevant.
Core Concepts¶
Cancellation¶
Coroutine cancellation is cooperative. It works well when code reaches suspension points or checks cancellation explicitly.
Exceptions¶
Exception behavior depends on:
- coroutine builder (
launchvsasync) - parent-child hierarchy
- supervisor boundaries
- where exceptions are observed
Internal Implementation¶
Cancellation is represented by job state changes and propagated through job hierarchy.
A coroutine that never suspends or checks cancellation may continue running longer than expected.
JVM / Compiler Behavior¶
Suspend functions cooperate with cancellation through coroutine machinery, not through thread interruption alone.
CoroutineExceptionHandler is only for uncaught exceptions; it is not a general substitute for structured error handling.
Code Examples¶
while (isActive) {
doWorkChunk()
}
try {
doWork()
} catch (e: CancellationException) {
throw e
}
Common Interview Questions¶
- Q: Why is cancellation called cooperative? A: Tie Kotlin language features to production outcomes: safety, readability, testability, and runtime or allocation tradeoffs when relevant.
- Q: Why should
CancellationExceptionusually be rethrown? A: Tie Kotlin language features to production outcomes: safety, readability, testability, and runtime or allocation tradeoffs when relevant. - Q: Why doesn't
CoroutineExceptionHandlercatch everything? A: Lead with correctness then throughput: choose dispatcher by workload type, keep critical sections small, cap parallelism, and monitor tail latency and queue depth.
Production Considerations¶
Common bugs:
- swallowing cancellation accidentally
- blocking threads inside coroutines
- assuming
try/catchand handler behavior are identical across builders
Performance Insights¶
Cancellation responsiveness matters for UI, battery, and resource cleanup. Poor cancellation behavior can waste work and degrade UX.
Senior-Level Insights¶
Good coroutine engineers think about cancellation and exception strategy during API design, not only when debugging failures.