async/await Exception Propagation
Understand how exceptions from async propagate and when to use try-await.
async/await Exception Propagation is a free Kotlin Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Kotlin Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
async Stores Exceptions
Unlike launch, async stores the exception in the returned Deferred. It is only rethrown when you call await().
import kotlinx.coroutines.*
fun main() = runBlocking {
val deferred = async {
throw RuntimeException("async error")
}
try {
deferred.await() // exception rethrown here
} catch (e: RuntimeException) {
println("Caught: ${e.message}")
}
}Exception Without await()
If you never call await(), the exception is silently discarded with a regular Job parent. Prefer supervisorScope + always await.
import kotlinx.coroutines.*
fun main() = runBlocking {
// Exception stored in deferred, never retrieved:
val d = async { throw RuntimeException("lost exception") }
delay(100) // d has failed — exception never surfaced
println("d.isCancelled: ${d.isCancelled}")
}async Under coroutineScope
Under a regular coroutineScope, if an async child throws and the exception propagates (not caught), it cancels the scope and all siblings.
import kotlinx.coroutines.*
fun main() = runBlocking {
try {
coroutineScope {
val a = async { "A" }
val b = async { throw RuntimeException("B failed") }
println(a.await())
println(b.await()) // propagates, cancels scope
}
} catch (e: RuntimeException) {
println("Scope failed: ${e.message}")
}
}async Under supervisorScope
Under supervisorScope, exceptions from async do NOT propagate to siblings. Each await()` must be wrapped individually.
import kotlinx.coroutines.*
fun main() = runBlocking {
supervisorScope {
val a = async { "A" }
val b = async { throw RuntimeException("B failed") }
println(a.await())
try { println(b.await()) }
catch (e: RuntimeException) { println("b failed: ${e.message}") }
}
}awaitAll for Multiple Async
awaitAll(d1, d2, d3) awaits all deferreds. If any fails, it throws immediately and cancels the others.
import kotlinx.coroutines.*
fun main() = runBlocking {
try {
val results = awaitAll(
async { "result1" },
async { throw RuntimeException("task 2 failed") },
async { "result3" }
)
println(results)
} catch (e: Exception) {
println("awaitAll failed: ${e.message}")
}
}runCatching with async
Wrap each await() in runCatching to collect results and errors without short-circuiting.
import kotlinx.coroutines.*
fun main() = runBlocking {
supervisorScope {
val deferreds = listOf(
async { "A" },
async { throw RuntimeException("B") },
async { "C" }
)
val results = deferreds.map { runCatching { it.await() } }
results.forEach { println(it) }
}
}Parallel Tasks with Error Accumulation
Collect all failures from parallel async tasks and report them together rather than failing fast.
import kotlinx.coroutines.*
fun main() = runBlocking {
val tasks = listOf("a", "b", "c")
val results = supervisorScope {
tasks.map { t ->
async {
if (t == "b") throw RuntimeException("b failed")
t.uppercase()
}
}.map { runCatching { it.await() } }
}
val errors = results.filter { it.isFailure }
val successes = results.mapNotNull { it.getOrNull() }
println("Success: $successes, Errors: ${errors.size}")
}Exception Type Preservation
Exceptions thrown inside async preserve their type. Catch the specific exception type at await() for precise error handling.
import kotlinx.coroutines.*
class NetworkException(msg: String) : RuntimeException(msg)
fun main() = runBlocking {
val d = async { throw NetworkException("timeout") }
try {
d.await()
} catch (e: NetworkException) {
println("Network error: ${e.message}")
} catch (e: Exception) {
println("Other error: ${e.message}")
}
}Deferred.getCompleted() for Non-Suspending Check
After join(), use getCompleted() to retrieve the result synchronously. It throws if the deferred failed.
import kotlinx.coroutines.*
fun main() = runBlocking {
val d = async { 42 }
d.join() // wait without caring about result
try {
val result = d.getCompleted() // synchronous — no suspend
println("Result: $result")
} catch (e: Exception) {
println("Failed: ${e.message}")
}
}Structured Concurrency and async
Under structured concurrency, an async deferred is always linked to its parent scope. When the scope is cancelled, the deferred is cancelled too — no orphan tasks.
import kotlinx.coroutines.*
fun main() = runBlocking {
val scope = CoroutineScope(SupervisorJob())
val d = scope.async {
delay(1000)
"result"
}
scope.cancel() // cancels d too
try { d.await() }
catch (e: CancellationException) { println("Cancelled as expected") }
}Best Practice: Always Await
Always await() every async deferred, even if you do not need the result. This surfaces exceptions and prevents silent failures.
import kotlinx.coroutines.*
fun main() = runBlocking {
supervisorScope {
val d = async {
// do background work
"done"
}
// Always await:
val result = runCatching { d.await() }
println(result)
}
}Quick Check
When does the exception from an async { throw ... } block surface?
Recap
async stores exceptions in the Deferred; they surface at await(). Under coroutineScope, propagation cancels siblings. Under supervisorScope, each await must handle its own failure. Always await every deferred.
Frequently asked questions
Is the “async/await Exception Propagation” lesson free?
Yes — the full text of “async/await Exception Propagation” is free to read here on the web, and the Kotlin Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Kotlin Academy course, upgrade to CoddyKit PRO.
What will I learn in “async/await Exception Propagation”?
Understand how exceptions from async propagate and when to use try-await. You practise Kotlin Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Kotlin Academy?
No prior experience is required. Kotlin Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “async/await Exception Propagation” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Kotlin Academy lesson?
Yes. Every Kotlin Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- SupervisorJob vs Job: Failure Isolation
- CoroutineExceptionHandler: Global Uncaught Handler
- async/await Exception Propagation
- Designing Resilient Coroutine Architectures