Junior — Middle
Can you explain the purpose and operation of ExceptionHandler when using coroutines in Kotlin?
sobes.tech AI
Answer from AI
In Kotlin, there is a special mechanism for handling exceptions in coroutines — CoroutineExceptionHandler. Its task is to catch unhandled exceptions that occur in coroutines and execute a specified handling code (for example, logging or showing a message to the user).
CoroutineExceptionHandler is a coroutine context element that can be added when launching a coroutine. It only triggers for exceptions that were not caught inside the coroutine itself (for example, in try-catch blocks).
Example of usage:
val handler = CoroutineExceptionHandler { _, exception ->
println("Caught exception: ${exception.localizedMessage}")
}
GlobalScope.launch(handler) {
throw RuntimeException("Error in coroutine")
}
Here, if an exception occurs in the coroutine, it will be caught and handled in handler. This is especially useful for centralized error handling in asynchronous code.