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

neworldlt

10/05/2020, 9:11 AM
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

gildor

10/05/2020, 9:12 AM
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

neworldlt

10/05/2020, 9:14 AM
always? It means
runCatching()
with failback is illegal inside coroutines
g

gildor

10/05/2020, 9:14 AM
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

neworldlt

10/05/2020, 9:18 AM
Ok. I suppose the worst case of hiding cancellation is to let other coroutines continue to work unexpectedly. Am I right?
g

gildor

10/05/2020, 9:19 AM
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

neworldlt

10/05/2020, 9:23 AM
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

streetsofboston

10/05/2020, 11:44 AM
That's why I added this bug/feature-request a while ago: https://github.com/Kotlin/kotlinx.coroutines/issues/1814
a

allan.conda

11/02/2020, 2:47 AM
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

streetsofboston

11/02/2020, 2:48 AM
Yes, but without a (new) lint .
👍 1
6 Views