Junior — Middle
In what cases is CoroutineExceptionHandler used in coroutines?
sobes.tech AI
Answer from AI
CoroutineExceptionHandler is used for handling unhandled exceptions in coroutines that are launched in a global or supervisor context.
It is applied when you need to centrally catch errors that were not caught inside the coroutine, to prevent application crashes or for error logging.
Example of usage:
val handler = CoroutineExceptionHandler { _, exception ->
println("Caught $exception")
}
GlobalScope.launch(handler) {
throw RuntimeException("Test exception")
}
Important: CoroutineExceptionHandler does not catch exceptions in coroutines launched via async if their result was not obtained (await). For such cases, you need to use try-catch inside the coroutine.