DEV Community

myougaTheAxo
myougaTheAxo

Posted on

Coroutine Exception Handling - supervisorScope and CoroutineExceptionHandler

Coroutine Exception Handling — supervisorScope & CoroutineExceptionHandler

Coroutines require careful exception handling. A failure in one child can cancel siblings. Use supervisorScope to isolate failures and CoroutineExceptionHandler for global handling.

supervisorScope Pattern

viewModelScope.launch {
    supervisorScope {
        val task1 = async { fetchData1() }
        val task2 = async { fetchData2() }

        task1.await() // failure doesn't cancel task2
        task2.await()
    }
}
Enter fullscreen mode Exit fullscreen mode

Global Exception Handler

val handler = CoroutineExceptionHandler { _, exception ->
    Log.e("Coroutine", "Caught: ${exception.message}")
    showErrorUI(exception)
}

viewModelScope.launch(handler) {
    riskyOperation()
}
Enter fullscreen mode Exit fullscreen mode

Best Practice

Use supervisorScope for independent tasks and CoroutineExceptionHandler for UI notifications.


8 production-ready Android app templates on Gumroad.
Browse templatesGumroad

Top comments (0)