Exception handling in coroutines
Why it matters
- Uncaught exceptions in
launchcan crash the entire application process. - Swallowing
CancellationExceptionlets code keep running after its screen is gone, writing stale state or showing false errors. - Understanding the difference between
coroutineScopeandsupervisorScopeis critical for building resilient architectures. - Interviewers use exception propagation to test if you actually understand structured concurrency or just use
try-catchblindly.
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.
coroutineScope | supervisorScope | |
|---|---|---|
| A child fails | The other children are cancelled | The other children keep running |
| What the caller sees | coroutineScope rethrows the child's exception | Nothing; the child must handle its own failure |
| Its own block throws | The exception is rethrown | The 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 theCoroutineExceptionHandlerin 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 theDeferredand thrown when you callawait(). Nothing is reported if you never callawait(). ACoroutineExceptionHandlerhas no effect on it.- An
asyncthat is a child of a regular Job behaves like any other child: its failure cancels the parent straight away, even beforeawait()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.
Notes
- Prefer
try/catcharound the suspend call that can fail, inside the coroutine, catching specific types such asIOException. - Always rethrow
CancellationExceptionif you catchExceptionorThrowable. - Use
supervisorScopefor independent tasks where one failure should not stop the others, and handle each child's error. CoroutineExceptionHandleris used only by alaunchat the top: a root coroutine or a direct child of aSupervisorJoborsupervisorScope. On any other child it is ignored, because the child reports to its parent instead.- A
CoroutineExceptionHandlercannot recover: by the time it runs, the coroutine has already failed. Use it to log and report, not to retry. viewModelScopehas no exception handler, so an exception that escapes aviewModelScope.launchcrashes the app.withContextandcoroutineScoperethrow a failure to their caller, so atry/catcharound them works.runCatchingcatchesCancellationExceptiontoo; avoid it around suspend calls, or rethrow cancellation from it.- Use
withContext(NonCancellable)for suspend cleanup infinallyblocks 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
asyncdoes not cancel its sibling because the parent is a supervisor, and the exception reaches you only throughawait(). - In case 3, the inner child's failure goes up to the outer
launch. The outerlaunchis a direct child of aSupervisorJob, so nobody above handles it, and the handler in its context receives it. A handler passed only to the innerlaunchwould be ignored. - In case 4,
finallyruns on cancellation, andNonCancellablelets the cleanup suspend for 50 ms instead of failing at once.
In production
- Crashlytics showed
retrofit2.HttpException: HTTP 500crashing the app from a refresh inviewModelScope.launch. - The code caught
IOExceptionaround the Retrofit call, which handled no-network errors. HttpExceptionis not anIOException, so it escaped thelaunch.viewModelScopehas no exception handler, so the app crashed.
- The repository now catches
IOExceptionandHttpExceptionand returns a sealed result with network and server error cases. It letsCancellationExceptionpass 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.
- Some audio recordings could not be played back if the user left the screen while recording.
- The recording loop ran in
viewModelScope, andfinallycalled the suspend functionrecorder.finalizeFile(), which writes the file header. - When the ViewModel was cleared, the coroutine was cancelled, and
finalizeFile()threwCancellationExceptionat its first suspension point, so the header was never written.
- 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
Exceptionand do not rethrowCancellationException, 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 usetry/catchinside the child. - Expecting a handler to catch async failures.
CoroutineExceptionHandleris never used forasync. Its exception comes out ofawait(), 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 fromwork(), becauselaunchreturns straight away. Put thetryinside the coroutine. - Using runCatching in suspending code.
runCatchingcatchesThrowable, includingCancellationException, so code keeps running after cancellation. - Assuming async hides exceptions. Under a regular Job, an
asyncfailure cancels the parent immediately, even if you have not calledawait()yet. - Using supervisorScope and handling nothing. In a
supervisorScope, a failedlaunchchild 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.
- Create
suspend fun fetchData(id: Int): Stringthat callsdelay(300)and throwsIOException("source " + id + " failed")whenid == 1, otherwise returns"data " + id. - Create
suspend fun repositoryFetchAll(): List<String>that usessupervisorScopeto startfetchData(1)andfetchData(2)withasync. Wrap eachawait()intry/catch (e: IOException)and use"fallback"for a failed source. - In
repositoryFetchAll, wrap the body intry/finally. In thefinallyblock, usewithContext(NonCancellable)todelay(50)and print "Cleaning up repository resources...". - In
main, userunBlocking. First callrepositoryFetchAll()and print the list. Then launch it again, cancel the job after 100 ms withcancelAndJoin(), 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.