Middle
What are the differences between launch and async in error handling context?
sobes.tech AI
Answer from AI
In launch, errors propagate directly to the parent coroutine context, which leads to application failure if they are not handled. In async, errors are deferred and only occur when .await() is called.
For example:
fun main() = runBlocking {
// launch: error causes scope to fail
val job = launch {
throw IllegalStateException("Error in launch")
}
job.join() // Waits for job completion, if an error occurs, the job will be canceled
// async: error is deferred until await
val deferred = async {
throw IllegalStateException("Error in async")
"Result" // This code will not be executed
}
try {
deferred.await() // The deferred error will be thrown here
} catch (e: IllegalStateException) {
println("Caught error: ${e.message}")
}
}