Part 14 / Topic 6 of 7
Exception handling in coroutines
A try/catch around a suspend call works exactly like around an ordinary one:
suspend fun riskyCall(): String {
delay(50)
throw IllegalStateException("payment gateway timeout")
}
try {
riskyCall()
} catch (e: IllegalStateException) {
println("caught: ${e.message}")
}
An exception that escapes launch uncaught (no try/catch around the call site, because
there usually isn't one for fire-and-forget work) needs a different net: a
CoroutineExceptionHandler on the scope logs it as a last resort, and a SupervisorJob
stops that one failure from cancelling the whole scope (the same isolation supervisorScope gave
individual children in Section 3, but for a long-lived scope rather than one block).
val handler = CoroutineExceptionHandler { _, e -> println("handler logged: ${e.message}") }
val scope = CoroutineScope(SupervisorJob() + handler)
scope.launch { error("printer offline") }.join()
val ok = scope.launch { println("other jobs on this scope keep running") }
ok.join()
scope.cancel()
The runCatching pitfall: runCatching wraps any thrown Throwable into a Result,
including CancellationException. If you don't check for it and rethrow, a cancelled coroutine
can get swallowed as if it were just a normal failure, and cancellation effectively stops
working.
val job = launch {
val result = runCatching {
delay(1000)
"never gets here"
}
result.onFailure { e ->
if (e is CancellationException) throw e // rethrow, or cancellation stops working
println("real failure: ${e.message}")
}
println("unreachable if cancelled correctly")
}
delay(50)
job.cancelAndJoin()
println("job cancelled cleanly: ${job.isCancelled}")
caught: payment gateway timeout
handler logged: printer offline
other jobs on this scope keep running
job cancelled cleanly: true
Note what's missing from that output: no "real failure" and no "unreachable..." line. The
job coroutine was cancelled 50ms in, while still inside delay(1000); runCatching caught the
resulting CancellationException, the if (e is CancellationException) throw e check rethrew
it immediately, and the coroutine stopped there -- exactly as a cancelled coroutine should.
Full program: examples/06_exception_handling.kt.
Done here? The practice set for Part 14 — including the solutions — is on the part page.