Proper exception handling in Kotlin Coroutines is crucial for building robust, reliable applications.
CoroutineExceptionHandler
val exceptionHandler = CoroutineExceptionHandler { _, exception ->
println("Caught: ${exception.message}")
}
@Composable
fun ExceptionHandlingScreen() {
val scope = rememberCoroutineScope()
Button(
onClick = {
scope.launch(exceptionHandler) {
throw RuntimeException("Something went wrong")
}
}
) {
Text("Trigger Error")
}
}
SupervisorJob for Independent Task Handling
SupervisorJob prevents child coroutine failures from cancelling siblings:
@Composable
fun IndependentTasks() {
val scope = rememberCoroutineScope() + SupervisorJob()
Button(
onClick = {
scope.launch {
try {
performTask1()
} catch (e: Exception) {
println("Task 1 failed: ${e.message}")
}
}
scope.launch {
try {
performTask2()
} catch (e: Exception) {
println("Task 2 failed: ${e.message}")
}
}
}
) {
Text("Run Tasks")
}
}
suspend fun performTask1() { /* Implementation */ }
suspend fun performTask2() { /* Implementation */ }
Try-Catch in Coroutines
@Composable
fun SafeNetworkCall() {
val scope = rememberCoroutineScope()
var result by remember { mutableStateOf("") }
Button(
onClick = {
scope.launch {
try {
result = fetchData()
} catch (e: Exception) {
result = "Error: ${e.message}"
}
}
}
) {
Text("Fetch Data")
}
Text(result)
}
suspend fun fetchData(): String {
// Your network call
return "Data"
}
Proper exception handling prevents crashes and improves user experience.
8 Android app templates available on Gumroad
Top comments (0)