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
Joffrey
04/04/2022, 3:14 PM
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
aballano
04/04/2022, 3:22 PM
yes, that's what I understood too, but was wondering for any docs so I can properly present the issue to my team 😄
r
Rick Clephas
04/04/2022, 5:53 PM
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.