https://kotlinlang.org logo
#coroutines
Title
# coroutines
g

Gleno

07/30/2021, 7:24 PM
I’m sure this has been asked to death, but should I always rethrow the
CancellationException
?
n

Nick Allen

07/30/2021, 9:49 PM
That's been my experience: always rethrow. If your coroutine is cancelled then you could mess up cancellation by swallowing it. I can kinda imagine code where you do want to catch it based on some child job being cancelled. Consider:
Copy code
val task = async {
    figureSomethingOut()
}
otherThing.doOnSomeEvent {
    result.cancel()
}
val result = try {
    task.await()
} catch (e: CancellationException) {
    ensureActive()
    figureOutSomethingElse()
}
The
ensureActive
call will rethrow the
CancellationException
if it is meant for the "outer" coroutine. I'd definitely look for an alternative though rather than write such code just for clarity. For example,
join
does throw like
await
, and then the
Deferred
could be inspected to see if it was cancelled or finished.
2 Views