Coroutine Exception Handling
Coroutine Exception Handling (Kotlin)
Handling exceptions in Kotlin Coroutines is different from normal try–catch, because coroutines are asynchronous and follow structured concurrency.
This guide explains all important rules, patterns, and best practices.
1. Basic Rule (Most Important)
❗ Exceptions in coroutines are propagated to the parent scope
-
Child coroutine fails → parent fails
-
Parent cancels all children
2. try–catch with launch (Won’t Work)
❌ This does NOT catch exceptions:
Reason:
-
launchis fire-and-forget -
Exception happens later
3. Correct try–catch Inside Coroutine
✅ Catch inside the coroutine:
4. async Exception Handling (Important Difference)
async stores exception until await() is called.
5. CoroutineExceptionHandler
Used for uncaught exceptions in launch.
Rules:
-
Works with
launch -
❌ Does NOT work with
async -
Handles last-resort exceptions
6. supervisorScope (Prevent Cascade Failure)
By default:
-
One child fails → all siblings cancel
supervisorScope changes this behavior.
✅ Child 2 continues running
7. SupervisorJob
Used at scope level.
8. Exception Handling in coroutineScope
✔ Exception propagates to parent
9. CancellationException (Special Case)
-
❌ Not treated as error
-
❌ Not caught by handler
-
Used internally for cancellation
10. Flow Exception Handling
❌ try–catch won’t work outside
✅ Use catch operator
11. Best Practices (Very Important)
✔ Use try–catch inside coroutine
✔ Use async + await() for result-based error handling
✔ Use CoroutineExceptionHandler for logging
✔ Use SupervisorJob in ViewModels
✔ Use Flow catch {} for streams
12. Android MVVM Example
Summary Table
| Scenario | Solution |
|---|---|
launch error |
try–catch inside |
async error |
await + try–catch |
| Global error | CoroutineExceptionHandler |
| Prevent cascade | SupervisorJob |
| Flow error | catch operator |
