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

肖志康

09/25/2023, 9:16 AM
Is it safe to catch all exception when calling a suspend function? For more specific, will it break the propagation of CancellationException to cancel other job?
Lets say I am writting the following code:
Copy code
suspend fun myBizFun() {
    // Some biz logic, may throw IOException or CancellationException
}

suspend fun callSite() {
    try {
        myBizFun()
    } catch (e: Exception) {
        // print log
        // Not re-throwing e even if it is CancellationException
    }
}
j

Joffrey

09/25/2023, 9:18 AM
That will break the cancellation mechanism, yes
But also, catching all exceptions is a bad idea in general, unless you're writing some framework code
u

肖志康

09/25/2023, 9:22 AM
Actually I am writting in app layer, and most of it is: If any exception occurs, show an error image or make a toast, so I wrote a lot of
Copy code
try {
        myBizFun()
    } catch (ce: CancellationException) {
        throw ce
    } catch (e: Exception) {
        // print log
    }
s

Sam

09/25/2023, 10:14 AM
That's a reasonable solution, but I prefer this one even more:
Copy code
try {
    myBizFun()
} catch (e: Exception) {
    coroutineContext.ensureActive()
    // print log
}
Calling
ensureActive()
is the simplest way to make sure exception handling doesn't break cancellation, and it solves various issues that can arise with manual handling of cancellation exceptions. Plus it's even fewer lines of code 👌
🙌 1
u

肖志康

09/25/2023, 10:56 AM
@Sam thank you, that's very nice
s

Sam

09/25/2023, 10:59 AM
Thanks! I wrote an article all about it if you are ever interested in learning more: https://medium.com/better-programming/the-silent-killer-thats-crashing-your-coroutines-9171d1e8f79b
t

taer

09/25/2023, 6:35 PM
I was gonna post your article @Sam That was a really good writeup.
thank you color 1
s

Scott Rankin

09/28/2023, 6:09 PM
Same. That article is great and scared me a bit after reading it @Sam A co-worker sent it around a few days ago. I'm fairly certain one of our customers recently ran into this.