Junior — Middle
What approaches and methods are used for error handling in Kotlin coroutines?
sobes.tech AI
Answer from AI
In Kotlin, there are several approaches to error handling in coroutines:
- try-catch inside a coroutine — the simplest way to handle exceptions. You can wrap code inside
launchorasyncin atry-catchblock.
launch {
try {
// code that may throw an exception
} catch (e: Exception) {
// error handling
}
}
- CoroutineExceptionHandler — a special handler that can be passed into the coroutine context. It catches unhandled exceptions in coroutines launched via
launch.
val handler = CoroutineExceptionHandler { _, exception ->
println("Caught $exception")
}
GlobalScope.launch(handler) {
throw RuntimeException("Error")
}
- Error handling in async/await — when using
async, exceptions are not thrown immediately but upon callingawait(). Therefore,await()should be wrapped in atry-catch.
val deferred = async {
// code
throw Exception("Error")
}
try {
deferred.await()
} catch (e: Exception) {
// error handling
}
- SupervisorJob and SupervisorScope — allow isolating errors of child coroutines so that one error does not cancel the entire parent scope.
Thus, the choice of method depends on the context and the type of coroutine (launch or async).