Junior — Middle
What are the differences in error handling between using launch and async/await in coroutines?
sobes.tech AI
Answer from AI
In Kotlin coroutines, launch and async differ in error handling:
-
launch: starts a coroutine that does not return a result. If an exception occurs inside
launch, it is passed to the CoroutineExceptionHandler or propagated to the parent context, which may lead to cancellation of the parent coroutine. -
async: starts a coroutine that returns a Deferred — a deferred result. Exceptions inside
asyncare not thrown immediately but are deferred untilawait()is called. Ifawait()is not called, the error may go unnoticed.
Example:
val job = launch {
throw Exception("Error in launch")
}
val deferred = async {
throw Exception("Error in async")
}
runBlocking {
job.join() // exception will be handled here
try {
deferred.await() // exception is thrown here
} catch (e: Exception) {
println("Caught error: ${e.message}")
}
}
Thus, launch immediately signals an error, while async does so only when attempting to get the result.