r/Kotlin • u/yogirana5557 • 13h ago
"Always rethrow CancellationException" quietly broke our withTimeout fallback in production
We added a rule across our shared KMP/Android modules to stop swallowing CancellationException inside generic catch (e: Exception) blocks. Standard hygiene, until network timeouts started aborting a whole sync job instead of hitting the fallback path.
Took a few traces to spot it: TimeoutCancellationException is a subclass of CancellationException. So a strict if (e is CancellationException) throw e guard treats a 2-second timeout identically to scope cancellation:
val delta = try {
withTimeout(2_000) { api.fetchDelta() }
} catch (e: TimeoutCancellationException) {
loadStaleCache() // must sit BEFORE CancellationException (and catches inner timeouts too)
} catch (e: CancellationException) {
throw e
}
// Idiomatic fix: only THIS timeout returns null; parent cancellation still propagates
val safeDelta = withTimeoutOrNull(2_000) { api.fetchDelta() } ?: loadStaleCache()Anyone else get bitten by CancellationException subclassing when cleaning up runCatching blocks? (I keep similar Kotlin concurrency notes in the repo pinned on u/yogirana5557.)
