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.
0
0
Exception handling in coroutines in Android Kotlin
Introduction
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.Android Kotlin
val handler = CoroutineExceptionHandler { _, exception ->
println("Caught $exception")
}
GlobalScope.launch(handler) {
throw RuntimeException("Oops!")
}Sample App
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.
CoroutineExceptionHandler helps handle exceptions globally.
Handling exceptions keeps your app stable and user-friendly.