Is it safe to catch all exception when calling a s...
# coroutines
u
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
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
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
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 👌
🙌 2
u
@Sam thank you, that's very nice
s
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
I was gonna post your article @Sam That was a really good writeup.
thank you color 1
s
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.