Kotlin
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
105: Coroutine Exception Handlers In Depth
If you've been playing around with coroutines, you've probably noticed that exception handling isn't as straightforward as wrapping everything in a giant try-catch block. When you start dealing with structured concurrency, the way exceptions propagate up the tree can feel a bit like a game of hot potato. Let's clear up the confusion.
Why is my CoroutineExceptionHandler being completely ignored?
This is the most common frustration I see. You define a CoroutineExceptionHandler, you pass it into your launch block, and yet the app still crashes with an unhandled exception. Here is the rule: a CoroutineExceptionHandler only works when it is installed in the root coroutine of a scope.
If you add a handler to a child coroutine, it's useless. Why? Because in structured concurrency, a child always delegates its exception to its parent. The parent then tells its other children to cancel and finally handles the exception itself. If the handler isn't at the very top, it's simply skipped over.
val handler = CoroutineExceptionHandler { _, exception ->
println("Caught $exception!")
}
// This works because it's the root
val scope = CoroutineScope(Job() + handler)
scope.launch {
throw RuntimeException("Root failure")
}
// This DOES NOT work; the exception propagates to the parent scope
scope.launch {
launch(handler) {
throw RuntimeException("Child failure")
}
}
Wait, why does this work for launch but not for async?
I'll be honest: this trips everyone up. launch is "fire and forget," so it has no way to return a result to you. The only way to signal a failure is to throw the exception up the hierarchy. That's where the CoroutineExceptionHandler steps in to act as a last-resort safety net.
async, however, is designed to return a Deferred value. It treats an exception just like any other return value—it captures it and stores it inside that Deferred object. The exception isn't actually "thrown" until you call .await(). Because of this, a CoroutineExceptionHandler will never catch an exception from async; you're expected to use a standard try-catch block around the await() call.
val deferred = scope.async {
throw RuntimeException("Async failure")
}
try {
deferred.await()
} catch (e: Exception) {
println("Caught the async error here: ${e.message}")
}
How do I stop one failing task from killing my entire scope?
By default, if one child coroutine fails, it cancels its parent, which in turn cancels all other siblings. That's great for a tight sequence of dependent tasks, but it's a nightmare if you're building something like a dashboard that fetches data from five different APIs. If the "Weather API" fails, you still want the "Stock Prices" to show up.
This is where SupervisorJob comes in. A supervisor changes the rule: failure propagates downwards, but not upwards. When you combine a SupervisorJob with a CoroutineExceptionHandler, you get a robust system where individual failures are logged but don't trigger a chain reaction of cancellations.
Check out this pattern for a "Resilient Dashboard" fetcher:
val handler = CoroutineExceptionHandler { _, e ->
println("Logged error: ${e.message}")
}
// Use SupervisorJob so children don't kill each other
val dashboardScope = CoroutineScope(SupervisorJob() + handler)
fun loadDashboard() {
dashboardScope.launch {
// If this fails, the others keep running
launch { fetchWeather() }
launch { fetchNews() }
launch { fetchStocks() }
}
}
Just a heads-up: if you're using supervisorScope { ... } as a function instead of a SupervisorJob in a scope, remember that the handler still needs to be passed to the individual launch calls inside that block, because the supervisorScope itself doesn't "absorb" the exception—it just stops it from bubbling up.
📋 Practical Task
Exercise: Building a Fault-Tolerant Image Downloader
You are building a gallery app that downloads a list of images. Currently, if a single image URL is broken (throws an IOException), the entire download process stops, and no images are displayed.
Your Task:
- Create a
CoroutineScopethat uses aSupervisorJoband aCoroutineExceptionHandlerthat prints "Download failed for an image" to the console. - Inside this scope, launch three separate coroutines.
- The first and third coroutines should simulate a successful download (e.g., print "Image 1 downloaded").
- The second coroutine should throw an
IOException("404 Not Found"). - Verify that the
CoroutineExceptionHandlercatches the error, but more importantly, verify that the third image still finishes downloading successfully.
There are no comments for now.