DEV Community

myougaTheAxo
myougaTheAxo

Posted on

Coroutine Exception Handling: Robust Error Management

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")
    }
}
Enter fullscreen mode Exit fullscreen mode

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 */ }
Enter fullscreen mode Exit fullscreen mode

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"
}
Enter fullscreen mode Exit fullscreen mode

Proper exception handling prevents crashes and improves user experience.


8 Android app templates available on Gumroad

Top comments (0)