Hello folks, I got the idea that catching and not ...
# coroutines
a
Hello folks, I got the idea that catching and not rethrowing CancellationExceptions would be an anti-pattern but couldn't really find any documentation specifying that, does anyone know any docs saying this or any possible problems due to that? Thank you in advance!
1
j
I didn't find explicitly in the docs that you shouldn't do that, but it's explained that it's used for the cancellation mechanism, so if you don't rethrow you may break cancellation and structured concurrency
a
yes, that's what I understood too, but was wondering for any docs so I can properly present the issue to my team 😄
r
I don’t really think you can “break” cancellation or structured concurrency by catching the `CancellationException`s. However IMO it’s best to rethrow them anyway to make sure the code is cancelled asap. I think this becomes especially importent when you are mixing sync with async code. Not rethrowing the
CancellationException
allows sync code to run until the next suspend function that checks for cancellation. E.g https://pl.kotl.in/WMRrqJys3.
kotlinx.coroutines actually documents the cancellation behaviour with “prompt cancellation guarantee”: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/delay.html
a
thanks a lot @Rick Clephas very helpful!