Sobes.tech
Junior — Middle

Will the async execution be canceled if it contains a launch and an exception occurs?

sobes.tech AI

Answer from AI

In Kotlin Coroutines, if a coroutine is launched inside an async block using launch, an exception that occurs in launch will not automatically cancel the execution of async.

The reason is that async and launch create different coroutines with different error handling mechanisms:

  • async returns a Deferred, and errors within it are propagated when calling await().
  • launch starts a coroutine that does not return a result, and exceptions in it are handled via CoroutineExceptionHandler or lead to cancellation of the parent coroutine.

If launch is started inside async without explicitly linking it to its Job, an exception in launch will not cancel async. To ensure cancellation, you should launch launch in the same CoroutineScope or use SupervisorJob, or handle errors explicitly.

Example:

val deferred = async {
    launch {
        throw Exception("Error in launch")
    }
    // async execution continues
}

// Exception from launch will not affect deferred until `await()` is called