Skip to Content
Course content

105: Coroutine Exception Handlers In Depth

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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 CoroutineScope that uses a SupervisorJob and a CoroutineExceptionHandler that 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 CoroutineExceptionHandler catches the error, but more importantly, verify that the third image still finishes downloading successfully.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.