肖志康
09/25/2023, 9:16 AM肖志康
09/25/2023, 9:16 AMsuspend 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
}
}
Joffrey
09/25/2023, 9:18 AMJoffrey
09/25/2023, 9:18 AM肖志康
09/25/2023, 9:22 AMtry {
myBizFun()
} catch (ce: CancellationException) {
throw ce
} catch (e: Exception) {
// print log
}
Sam
09/25/2023, 10:14 AMtry {
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 👌肖志康
09/25/2023, 10:56 AMSam
09/25/2023, 10:59 AMtaer
09/25/2023, 6:35 PMScott Rankin
09/28/2023, 6:09 PM