Questions
KotlinIntermediate4 min
Exception Handling in Coroutine?
Answer
Handling exceptions in coroutines depends on the scope and builder.
1. try-catch
The most basic way. Works inside `launch` or `async` (when you call await).
```kotlin launch { try { doWork() } catch (e: Exception) { handleError(e) } } ```
2. CoroutineExceptionHandler
A context element to handle uncaught exceptions in `launch`.
- Note: Does NOT catch exceptions in `async`.
- Note: Only works in the root coroutine or a SupervisorJob.
```kotlin val handler = CoroutineExceptionHandler { _, exception -> println("Caught $exception") } scope.launch(handler) { throw RuntimeException("Boom") } ```
3. Async / Await
Exceptions in `async` are deferred until you call `.await()`. You must wrap the `await()` call in try-catch.
1:1 Mentorship
Get personalized guidance from a Google Developer Expert. Accelerate your career with dedicated support.
Personalized Learning Path
Mock Interviews & Feedback
Resume & Career Guidance
Share & Help Others
Help fellow developers prepare for interviews
Sharing helps the Android community grow 💚