Junior — Middle
What is the role and application of CoroutineExceptionHandler in error handling within coroutines?
sobes.tech AI
Answer from AI
CoroutineExceptionHandler is an interface in Kotlin Coroutines that allows centralized handling of unhandled exceptions occurring in coroutines.
Role and application:
- Enables defining error handling logic for errors not caught within the coroutine itself.
- Used for global exception handling, such as logging or user notification.
- Added to the coroutine context when it is launched.
Example of usage:
val handler = CoroutineExceptionHandler { _, exception ->
println("Caught exception: $exception")
}
GlobalScope.launch(handler) {
throw RuntimeException("Error in coroutine")
}
In this example, the exception thrown in the coroutine will be caught and handled by CoroutineExceptionHandler, preventing the application from crashing.