What is the best practice of rethrowing Cancellati...
# coroutines
n
What is the best practice of rethrowing CancellationException if I am catching all exceptions? Do I need to rethrow CancellationException at all?
Copy code
val foo = runCatching { bar() }.getOrNull()  // or similar try-catch block
g
yes, you have to rethrow it, otherwise you hide cancellation
though, coroutine itself is cancelled, it will be checked only on next suspend point
n
always? It means
runCatching()
with failback is illegal inside coroutines
g
it’s not illigal, it’s just hides cancellation
you can implement own version of runCatching, if you use it a lot, which rethrows CancellationException
n
Ok. I suppose the worst case of hiding cancellation is to let other coroutines continue to work unexpectedly. Am I right?
g
yes, it delays cancellation, in some cases it can be a problem, anyway, it’s not good itself
this why catchign all exceptions is usually not a good idea
and was one of the main “cons” of adding Result to stdlib
n
I agree. But in many UI cases, you are needed failbacks for any error, so programmers just catch-all exception.
I am thinking to create a safe pair of
runCatching
and
try
versions only for coroutines with a lint check which do not permit the original version to be used in coroutines
Thanks for explanation! 🙇
s
That's why I added this bug/feature-request a while ago: https://github.com/Kotlin/kotlinx.coroutines/issues/1814
a
Just recently had the same concern, unfortunately the proposal above has not had an update in a while. @streetsofboston did you end up just using your solution in your project and wrote your own lint for it? Or perhaps you found a better approach for error handling (like not using the stdlib api at all)
s
Yes, but without a (new) lint .
👍 1