I’m sure this has been asked to death, but should ...
# coroutines
g
I’m sure this has been asked to death, but should I always rethrow the
CancellationException
?
n
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.