Junior — Middle
How to implement exception handling in asynchronous coroutines?
sobes.tech AI
Answer from AI
In Kotlin coroutines, to handle exceptions, you can use try-catch blocks within the coroutine itself or apply special constructs such as CoroutineExceptionHandler.
Example with try-catch inside a coroutine:
launch {
try {
val result = someSuspendFunction()
println(result)
} catch (e: Exception) {
println("Error: ${e.message}")
}
}
If the coroutine is launched via launch, unhandled exceptions are passed to CoroutineExceptionHandler:
val handler = CoroutineExceptionHandler { _, exception ->
println("Handled exception: ${exception.message}")
}
GlobalScope.launch(handler) {
throw RuntimeException("Error in coroutine")
}
Thus, you can flexibly manage errors in asynchronous code.