Sobes.tech
Junior — Middle

In which coroutine should an exception handler be added?

sobes.tech AI

Answer from AI

Exception handlers should be added to the top-level coroutine that is the root of coroutine launch, meaning where you want to control errors and prevent application crashes. Usually, this is a coroutine launched within a CoroutineScope of a component's lifecycle (e.g., ViewModel or Activity). For this, CoroutineExceptionHandler is used, which can be added to the coroutine's context when launching:

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

scope.launch(handler) {
    // coroutine code
}

It is important to remember that the handler only triggers for non-coroutine exceptions (e.g., in launch), while in async, exceptions need to be handled when calling await().

In which coroutine should an exception handler be… - sobes.tech