Exception handling in coroutines

You will understand how exceptions propagate through the coroutine hierarchy and how to handle them without breaking structured concurrency. About 25 minutes.

Why it matters

  • Uncaught exceptions in launch can crash the entire application process.
  • Swallowing CancellationException lets code keep running after its screen is gone, writing stale state or showing false errors.
  • Understanding the difference between coroutineScope and supervisorScope is critical for building resilient architectures.
  • Interviewers use exception propagation to test if you actually understand structured concurrency or just use try-catch blindly.

The simple explanation

  • A chain of command in a military unit.
  • If a soldier (child coroutine) fails, the sergeant (parent) is notified.
  • In a standard unit, if one soldier fails, the whole squad is disbanded (exception propagates up).
  • In a specialized unit (supervisor), the sergeant stays in command even if a soldier fails.

Exception handling in coroutines follows structured concurrency. Inside one coroutine, a suspend call throws like any function call, and try / catch works normally. When an exception escapes a coroutine, the coroutine fails and reports the exception to its parent. With a regular Job, the parent then cancels its other children and fails too, and the failure keeps moving up until it reaches a root coroutine or a supervisor.

coroutineScopesupervisorScope
A child failsThe other children are cancelledThe other children keep running
What the caller seescoroutineScope rethrows the child's exceptionNothing; the child must handle its own failure
Its own block throwsThe exception is rethrownThe exception is rethrown

Where an unhandled exception ends up depends on the builder of the coroutine at the top, the one with no parent to report to (a root coroutine, or a direct child of a supervisor):

  • launch: the exception goes to the CoroutineExceptionHandler in its context. Without one, it goes to the thread's uncaught exception handler, which on Android crashes the app.
  • async: the exception is stored in the Deferred and thrown when you call await(). Nothing is reported if you never call await(). A CoroutineExceptionHandler has no effect on it.
  • An async that is a child of a regular Job behaves like any other child: its failure cancels the parent straight away, even before await() is called.

CancellationException is special: it means normal cancellation, not failure. It does not cancel the parent and is never passed to an exception handler. If you catch it, rethrow it; otherwise your code keeps running after the coroutine was cancelled.

Job versus SupervisorJob when a child fails
Job versus SupervisorJob when a child fails With a regular Job, a failing child passes its exception up, the parent is cancelled and cancels its other child; with a SupervisorJob the failure is not passed up, so the scope stays active and the other child keeps running. REGULAR JOB SUPERVISORJOB EXCEPTION CANCELS NOT PASSED UP Parent Job cancelled, with all its children Child A throws Child B cancelled too Supervisor scope stays active Child C throws Child D keeps running
With a regular Job one failing child cancels the parent and its siblings; under a SupervisorJob the siblings keep running.

Notes

  • Prefer try / catch around the suspend call that can fail, inside the coroutine, catching specific types such as IOException.
  • Always rethrow CancellationException if you catch Exception or Throwable.
  • Use supervisorScope for independent tasks where one failure should not stop the others, and handle each child's error.
  • CoroutineExceptionHandler is used only by a launch at the top: a root coroutine or a direct child of a SupervisorJob or supervisorScope. On any other child it is ignored, because the child reports to its parent instead.
  • A CoroutineExceptionHandler cannot recover: by the time it runs, the coroutine has already failed. Use it to log and report, not to retry.
  • viewModelScope has no exception handler, so an exception that escapes a viewModelScope.launch crashes the app.
  • withContext and coroutineScope rethrow a failure to their caller, so a try / catch around them works.
  • runCatching catches CancellationException too; avoid it around suspend calls, or rethrow cancellation from it.
  • Use withContext(NonCancellable) for suspend cleanup in finally blocks that must run after cancellation.

Code example

Four ways an exception can be handled: at the call site, through await() in a supervisorScope, by a CoroutineExceptionHandler on a root coroutine, and cleanup that still runs after cancellation.

import kotlinx.coroutines.*

suspend fun loadProfile(fail: Boolean): String {
  delay(50)
  if (fail) throw IllegalStateException("profile failed")
  return "Ada"
}

fun main() = runBlocking {
  // 1. A suspend call throws like a normal function call
  try {
      loadProfile(fail = true)
  } catch (e: IllegalStateException) {
      println("1. caught at the call site: " + e.message)
  }

  // 2. async in supervisorScope keeps the exception until await()
  supervisorScope {
      val feed = async<String> {
          delay(100)
          throw IllegalStateException("feed failed")
      }
      val badges = async {
          delay(200)
          "3 badges"
      }
      try {
          feed.await()
      } catch (e: IllegalStateException) {
          println("2. await rethrew: " + e.message)
      }
      println("2. sibling still finished: " + badges.await())
  }

  // 3. CoroutineExceptionHandler in the context of a root coroutine
  val handler = CoroutineExceptionHandler { _, e -> println("3. handler got: " + e.message) }
  val scope = CoroutineScope(SupervisorJob() + handler)
  scope.launch {
      launch { throw IllegalStateException("child failed") }
  }.join()
  scope.cancel()

  // 4. Suspend cleanup after cancellation needs NonCancellable
  val job = launch {
      try {
          delay(1_000)
      } finally {
          withContext(NonCancellable) {
              delay(50)
              println("4. cleanup finished")
          }
      }
  }
  delay(100)
  job.cancelAndJoin()
  println("4. job cancelled: " + job.isCancelled)
}

Expected output:

1. caught at the call site: profile failed
2. await rethrew: feed failed
2. sibling still finished: 3 badges
3. handler got: child failed
4. cleanup finished
4. job cancelled: true
  • In case 2, the failed async does not cancel its sibling because the parent is a supervisor, and the exception reaches you only through await().
  • In case 3, the inner child's failure goes up to the outer launch. The outer launch is a direct child of a SupervisorJob, so nobody above handles it, and the handler in its context receives it. A handler passed only to the inner launch would be ignored.
  • In case 4, finally runs on cancellation, and NonCancellable lets the cleanup suspend for 50 ms instead of failing at once.

In production

Crash when the server returned 500
  • Crashlytics showed retrofit2.HttpException: HTTP 500 crashing the app from a refresh in viewModelScope.launch.
  • The code caught IOException around the Retrofit call, which handled no-network errors.
  • HttpException is not an IOException, so it escaped the launch. viewModelScope has no exception handler, so the app crashed.
The fix
  • The repository now catches IOException and HttpException and returns a sealed result with network and server error cases. It lets CancellationException pass through.
  • The ViewModel turns each case into an error message in its UiState.
  • An app-wide handler in Crashlytics still reports anything unexpected, but expected errors no longer reach it.
Corrupt recordings after leaving the screen
  • Some audio recordings could not be played back if the user left the screen while recording.
  • The recording loop ran in viewModelScope, and finally called the suspend function recorder.finalizeFile(), which writes the file header.
  • When the ViewModel was cleared, the coroutine was cancelled, and finalizeFile() threw CancellationException at its first suspension point, so the header was never written.
The fix
  • Wrapped the cleanup in withContext(NonCancellable) { recorder.finalizeFile() }.
  • Kept that block short and local (no network calls), because nothing can cancel it.
  • Added a test that cancels the recording job and checks the file has a valid header.

Common mistakes

  • Swallowing CancellationException. If you catch Exception and do not rethrow CancellationException, your code keeps running after the coroutine was cancelled and may write stale state.
  • Putting CoroutineExceptionHandler on a child coroutine. A child reports its failure to its parent, so the handler is ignored. Install it on the scope or the top-level launch, or use try / catch inside the child.
  • Expecting a handler to catch async failures. CoroutineExceptionHandler is never used for async. Its exception comes out of await(), or cancels the parent if the parent is a regular Job.
  • Wrapping launch in try / catch. try { scope.launch { work() } } catch (e: Exception) { } catches nothing from work(), because launch returns straight away. Put the try inside the coroutine.
  • Using runCatching in suspending code. runCatching catches Throwable, including CancellationException, so code keeps running after cancellation.
  • Assuming async hides exceptions. Under a regular Job, an async failure cancels the parent immediately, even if you have not called await() yet.
  • Using supervisorScope and handling nothing. In a supervisorScope, a failed launch child is not caught by the scope. Without a handler it still crashes the app.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“What happens to a parent coroutine if one of its children fails with an exception?”

“What is the difference between coroutineScope and supervisorScope?”

“Why should you rethrow CancellationException?”

“How does async handle exceptions differently than launch?”

Quiz

Which scope should you use if you want to run three independent API calls where one failure should not stop the others?

What happens if you catch 'Exception' in a coroutine but do not rethrow 'CancellationException'?

Where does a CoroutineExceptionHandler take effect?

If an async block fails inside a coroutineScope, what happens?

0 of 4 answered

Mini task

Task: The Resilient Repository

Goal: Implement a repository method that fetches data from two different sources. If one fails, the other should still complete, and you must ensure cleanup happens correctly.

  1. Create suspend fun fetchData(id: Int): String that calls delay(300) and throws IOException("source " + id + " failed") when id == 1, otherwise returns "data " + id.
  2. Create suspend fun repositoryFetchAll(): List<String> that uses supervisorScope to start fetchData(1) and fetchData(2) with async. Wrap each await() in try / catch (e: IOException) and use "fallback" for a failed source.
  3. In repositoryFetchAll, wrap the body in try / finally. In the finally block, use withContext(NonCancellable) to delay(50) and print "Cleaning up repository resources...".
  4. In main, use runBlocking. First call repositoryFetchAll() and print the list. Then launch it again, cancel the job after 100 ms with cancelAndJoin(), and print "cancelled".

Done Condition: The first run prints the cleanup message and then [fallback, data 2], so one failure did not stop the other source. The second run prints the cleanup message before "cancelled", even though the job was cancelled while the calls were still running.

Next: Flow basics: cold streams