Sometimes, things go wrong when your app does work in the background. Exception handling in coroutines helps you catch and manage these errors so your app doesn't crash.
When you want to safely run background tasks like fetching data from the internet.
When you need to handle errors without stopping the whole app.
When you want to show a friendly message if something fails during a background job.
When you want to log errors happening inside coroutines for debugging.
When you want to clean up resources if a coroutine fails.
Syntax
Android Kotlin
try {
// coroutine code that might throw an exception
} catch (e: Exception) {
// handle the exception here
}
Use try-catch inside coroutines to catch exceptions.
You can also use CoroutineExceptionHandler to handle exceptions globally.
Examples
This example shows catching an exception inside a coroutine launched with launch.
Android Kotlin
launch {
try {
val result = fetchData()
println("Data: $result")
} catch (e: Exception) {
println("Error: ${e.message}")
}
}
This example shows using CoroutineExceptionHandler to catch exceptions globally in a coroutine.
This program starts a coroutine that throws an exception after a delay. The CoroutineExceptionHandler catches the exception and prints a message. The program then prints that the coroutine finished.
Android Kotlin
import kotlinx.coroutines.*
fun main() = runBlocking {
val handler = CoroutineExceptionHandler { _, exception ->
println("Caught exception: ${exception.message}")
}
val job = launch(handler) {
println("Starting coroutine")
delay(500)
throw IllegalArgumentException("Something went wrong")
}
job.join()
println("Coroutine finished")
}
OutputSuccess
Important Notes
Exceptions in launch coroutines must be handled to avoid app crashes.
Exceptions in async coroutines are thrown when you call await().
Use CoroutineExceptionHandler for centralized error handling in coroutines.
Summary
Use try-catch blocks inside coroutines to catch exceptions.
2. Which of the following is the correct syntax to define a CoroutineExceptionHandler in Kotlin?
easy
A. val handler = CoroutineExceptionHandler(context, exception) -> println(exception)
B. val handler = CoroutineExceptionHandler { context, exception -> println(exception) }
C. val handler = CoroutineExceptionHandler(context) { exception -> println(exception) }
D. val handler = CoroutineExceptionHandler { exception -> println(exception) }
Solution
Step 1: Recall CoroutineExceptionHandler syntax
The handler takes a lambda with two parameters: CoroutineContext and Throwable.
Step 2: Match correct lambda parameters
val handler = CoroutineExceptionHandler { context, exception -> println(exception) } correctly uses (context, exception) parameters and prints the exception.
Final Answer:
val handler = CoroutineExceptionHandler { context, exception -> println(exception) } -> Option B
5. You want to handle exceptions globally for all coroutines in your app using CoroutineExceptionHandler. Which approach correctly applies this handler to multiple coroutines launched in different scopes?
hard
A. Create a single CoroutineExceptionHandler instance and pass it to each coroutine builder's context
B. Use try-catch inside each coroutine instead of CoroutineExceptionHandler
C. Attach CoroutineExceptionHandler only to the first coroutine launched
D. Use a global try-catch block outside all coroutine launches
Solution
Step 1: Understand global exception handling
CoroutineExceptionHandler can be reused by passing the same instance to multiple coroutine builders.
Step 2: Evaluate options for applying handler globally
Passing the handler to each coroutine context ensures all coroutines use the same global handler.
Final Answer:
Create a single CoroutineExceptionHandler instance and pass it to each coroutine builder's context -> Option A
Quick Check:
Reuse handler by passing to each coroutine = Create a single CoroutineExceptionHandler instance and pass it to each coroutine builder's context [OK]
Hint: Pass one handler instance to all coroutine contexts [OK]
Common Mistakes:
Using try-catch only inside coroutines misses global handling
Attaching handler to only one coroutine limits scope
Trying to catch exceptions outside coroutine scope
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.