{"id":1087,"date":"2026-11-27T13:51:00","date_gmt":"2026-11-27T12:51:00","guid":{"rendered":"https:\/\/grindloop.ai\/blog\/?p=1087"},"modified":"2026-11-27T10:53:23","modified_gmt":"2026-11-27T09:53:23","slug":"runcatching-swallows-cancellationexception","status":"publish","type":"post","link":"https:\/\/grindloop.ai\/blog\/runcatching-swallows-cancellationexception\/","title":{"rendered":"runCatching Swallows CancellationException: Why a Kotlin Polling Loop Freezes the App After onCleared"},"content":{"rendered":"<p>When runCatching swallows CancellationException, a coroutine can keep running after its scope is cancelled. A polling loop shows the worst case. You write <code>while (true)<\/code> around <code>runCatching { fetch(); delay(5_000) }<\/code> in <code>viewModelScope<\/code>. The user leaves the screen and the ViewModel is cleared. The next <code>delay<\/code> throws a CancellationException. runCatching catches it and returns a failure. The loop starts again at once. Every suspending call now throws without suspending. So the loop spins on the main thread and never lets it go. The previous screen freezes. Two causes stack here. runCatching catches every Throwable, including cancellation. A cancelled coroutine also never suspends again, so <code>while (true)<\/code> has nothing to stop it. The fix is to count a failure only while the coroutine is still active. Call <code>ensureActive()<\/code> in the catch before you wrap the error. Rethrowing every CancellationException looks simpler. But it silently ends the poller the first time a <code>withTimeout<\/code> fires.<\/p>\n\n<h2>An order-status poller that freezes the app after the screen closes<\/h2>\n\n<p>An order screen shows live delivery status. The ViewModel polls the API every few seconds. Each poll is wrapped in runCatching. A dropped connection should log a warning. Then the loop tries again.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"kotlin\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">class OrderStatusViewModel(private val api: OrderApi) : ViewModel() {\n    private val _status = MutableStateFlow(\"loading\")\n    val status: StateFlow&lt;String&gt; = _status\n\n    fun startPolling(orderId: String) {\n        viewModelScope.launch {\n            while (true) {\n                runCatching {\n                    _status.value = api.fetchStatus(orderId)\n                    delay(500)\n                }.onFailure { e -&gt;\n                    Log.w(\"OrderPoll\", \"poll failed\", e)\n                }\n            }\n        }\n    }\n}<\/pre>\n\n\n<p>We rebuilt this in plain Kotlin and ran it with Kotlin 2.4.20 and kotlinx.coroutines 1.11.0. A single-thread executor stands in for the main thread. A scope with a <code>SupervisorJob<\/code> on that thread stands in for <code>viewModelScope<\/code>. The fake API waits 100 ms and returns a status. Cancelling the scope plays the part of <code>onCleared()<\/code>. After the cancel, we posted one more task to the fake main thread. Then we waited a second for it to run.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">before cancel: polls=2 failures=0\nfirst failure: kotlinx.coroutines.JobCancellationException: Job was cancelled\n1s after cancel: polls=2 failures=1908104\nother main-thread work ran within 1s: false\njob still active? children=1<\/pre>\n\n\n<p>No poll succeeds after the cancel. The failure handler still ran 1.9 million times in one second. The task we posted never ran, because the loop held the thread. The job also never finished. In the app, <code>viewModelScope<\/code> runs on <code>Dispatchers.Main.immediate<\/code>, per the <a href=\"https:\/\/github.com\/androidx\/androidx\/blob\/androidx-main\/lifecycle\/lifecycle-viewmodel\/src\/commonMain\/kotlin\/androidx\/lifecycle\/viewmodel\/internal\/CloseableCoroutineScope.kt\" target=\"_blank\" rel=\"noopener\">AndroidX ViewModel scope source<\/a>. So the screen the user went back to stops responding. Android&#8217;s <a href=\"https:\/\/developer.android.com\/topic\/performance\/vitals\/anr\" target=\"_blank\" rel=\"noopener\">ANR documentation<\/a> says an ANR fires when input gets no response within 5 seconds. A real <code>Log.w<\/code> is slower than our counter, so the count would be lower. The loop still never ends.<\/p>\n\n<h2>runCatching swallows CancellationException because it catches every Throwable<\/h2>\n\n<p>runCatching is not coroutine-aware. Its <a href=\"https:\/\/github.com\/JetBrains\/kotlin\/blob\/master\/libraries\/stdlib\/src\/kotlin\/util\/Result.kt\" target=\"_blank\" rel=\"noopener\">source in the Kotlin standard library<\/a> is a <code>try<\/code> with one <code>catch (e: Throwable)<\/code>. CancellationException is a Throwable, so it becomes a <code>Result.failure<\/code> like any other error. Execution continues after the block.<\/p>\n\n<p>Coroutines need that exception to travel up. The <a href=\"https:\/\/kotlinlang.org\/docs\/coroutines-cancellation.html\" target=\"_blank\" rel=\"noopener\">Kotlin cancellation guide<\/a> warns that catching CancellationException can break cancellation propagation. If you must catch it, the guide says to rethrow it. Android&#8217;s <a href=\"https:\/\/developer.android.com\/kotlin\/coroutines\/coroutines-best-practices\" target=\"_blank\" rel=\"noopener\">coroutines best practices<\/a> give the same rule. They also recommend catching specific types such as <code>IOException<\/code> over <code>Exception<\/code> or <code>Throwable<\/code>.<\/p>\n\n<p><a href=\"https:\/\/github.com\/Kotlin\/kotlinx.coroutines\/issues\/1814\" target=\"_blank\" rel=\"noopener\">kotlinx.coroutines issue #1814<\/a> asks for a runCatching variant that rethrows cancellation. It was filed in February 2020 and is still open. The library still has no such function, so each team writes its own.<\/p>\n\n<h2>A cancelled coroutine never suspends again, so while (true) spins<\/h2>\n\n<p>The first cause alone would cost one extra iteration. The loop turns that into a spin. Cancellation in Kotlin is cooperative. The cancellation guide says a coroutine reacts only when it suspends or checks for cancellation explicitly. Our loop never checks. It relies on <code>delay<\/code> to stop it.<\/p>\n\n<p>A cancelled coroutine&#8217;s <code>delay<\/code> doesn&#8217;t wait. Its <a href=\"https:\/\/github.com\/Kotlin\/kotlinx.coroutines\/blob\/master\/kotlinx-coroutines-core\/common\/src\/Delay.kt\" target=\"_blank\" rel=\"noopener\">KDoc in kotlinx.coroutines<\/a> says a cancelled wait resumes at once with CancellationException. It also describes a prompt cancellation guarantee. In our run, a <code>delay<\/code> called after the cancel threw without waiting. The fake <code>fetchStatus<\/code> also calls <code>delay<\/code>, so it throws on entry. Each iteration now throws, gets caught and loops again. None of it suspends. The thread never comes free for other work.<\/p>\n\n<p>So the job can&#8217;t finish either. A job completes only when its body returns. This body is a <code>while (true)<\/code> that swallows every exit. That is why the repro still showed one live child after the cancel.<\/p>\n\n<h2>Count a failure only while the coroutine is still active<\/h2>\n\n<p>Wrap the error only after a cancellation check. If the coroutine was cancelled, <code>ensureActive()<\/code> throws its CancellationException. That ends the block, the loop and the job. If the coroutine is still active, the error is a real failure, so wrap it.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"kotlin\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">suspend inline fun &lt;T&gt; runSuspendCatching(block: () -&gt; T): Result&lt;T&gt; =\n    try {\n        Result.success(block())\n    } catch (e: Throwable) {\n        currentCoroutineContext().ensureActive()\n        Result.failure(e)\n    }\n\nclass OrderStatusViewModel(private val api: OrderApi) : ViewModel() {\n    private val _status = MutableStateFlow(\"loading\")\n    val status: StateFlow&lt;String&gt; = _status\n\n    fun startPolling(orderId: String) {\n        viewModelScope.launch {\n            while (true) {\n                runSuspendCatching {\n                    withTimeout(3_000) { api.fetchStatus(orderId) }\n                }.onSuccess { _status.value = it }\n                 .onFailure { e -&gt; Log.w(\"OrderPoll\", \"poll failed\", e) }\n                delay(5_000)\n            }\n        }\n    }\n}<\/pre>\n\n\n<p>Two other changes help. <code>delay<\/code> now sits outside the catching block, so a cancelled wait always ends the loop. A <code>withTimeout<\/code> caps a hung request, so one slow poll can&#8217;t stall the rest. We ran this exact ViewModel against stubs for <code>ViewModel<\/code> and <code>Log<\/code>. One poll hung for 4 seconds and one threw <code>IOException<\/code>. Both were logged. Polling went on after each. Then we ran the first harness with this helper. After the cancel, the job had no children left. The posted task ran on the fake main thread. The handler logged no failure for the cancel.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">ensureActive, normal before cancel: polls=4 failures=0 pollerAlive=true\nensureActive, normal after cancel: failures=0 children=0 mainFree=true<\/pre>\n\n\n<h2>Rethrowing every CancellationException ends the poller on its first timeout<\/h2>\n\n<p>The common helper rethrows any CancellationException. It fixes the spin. But <code>withTimeout<\/code> signals a timeout with <code>TimeoutCancellationException<\/code>. That class is a subclass of CancellationException. The coroutine that called it is not cancelled. A rethrow-all helper still throws it out of the loop. The <code>launch<\/code> then ends quietly, because a cancellation exception never crashes. We covered that silence in our post on <a href=\"https:\/\/grindloop.ai\/blog\/withtimeout-timeoutcancellationexception-stuck-spinner\/\">why withTimeout never crashes<\/a>.<\/p>\n\n<p>We made the fake API take 2 seconds and gave each poll a 300 ms timeout. Then we ran both helpers for 1.3 seconds before any cancel.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">ensureActive, timeout before cancel: polls=0 failures=2 pollerAlive=true\nrethrow-all, timeout before cancel: polls=0 failures=0 pollerAlive=false<\/pre>\n\n\n<p>The <code>ensureActive<\/code> helper logged two timeouts and kept polling. The rethrow-all helper logged nothing. Its poller was already dead. The status screen would show its last value forever with no error in the log. The <code>ensureActive<\/code> check tests whether this coroutine was cancelled. A timeout leaves the caller active, so it counts as a failed poll.<\/p>\n\n<h2>How to explain the frozen screen in a live-coding round<\/h2>\n\n<p>The round may hand you the poller and a report that the app freezes after Back. Walk from the symptom to both causes.<\/p>\n\n<ol>\n<li>Say the freeze starts at <code>onCleared()<\/code>. That is when <code>viewModelScope<\/code> is cancelled.<\/li>\n<li>Name the first cause. runCatching catches Throwable, so it turns the CancellationException into a failure.<\/li>\n<li>Name the second cause. A cancelled coroutine&#8217;s <code>delay<\/code> throws at once. So <code>while (true)<\/code> loops without suspending and holds the main thread.<\/li>\n<li>Explain why tests missed it. Nothing fails before the cancel. The cancel itself crashes nothing.<\/li>\n<li>Give the fix. Check <code>ensureActive()<\/code> before you wrap an error. Keep <code>delay<\/code> outside the catching block.<\/li>\n<li>Name the trap in the obvious fix. Rethrowing every CancellationException also rethrows a <code>withTimeout<\/code> timeout and ends the poller.<\/li>\n<\/ol>\n\n<p>Step 6 shows you tested the fix as well as the bug. Hass covers how reviewers find planted bugs like this one in <a href=\"https:\/\/grindloop.ai\/blog\/android-code-review-interview\/\">the Android code review interview<\/a>. Broad catches cause a related crash in our post on <a href=\"https:\/\/grindloop.ai\/blog\/viewmodelscope-launch-supervisorjob-crash\/\">viewModelScope.launch(SupervisorJob())<\/a>.<\/p>\n\n<h2>Answers that leave the poller spinning or dead<\/h2>\n\n<p>&#8220;Use <code>while (isActive)<\/code>.&#8221; It does stop the spin. In our run the loop exited after one more pass. But that pass logged a <code>JobCancellationException<\/code> as a failed poll. Any nested function that uses runCatching still swallows the cancel inside it.<\/p>\n\n<p>&#8220;Catch <code>Exception<\/code> instead of <code>Throwable<\/code>.&#8221; CancellationException extends <code>IllegalStateException<\/code>, so <code>catch (e: Exception)<\/code> still catches it. <a href=\"https:\/\/github.com\/Kotlin\/kotlinx.coroutines\/issues\/4073\" target=\"_blank\" rel=\"noopener\">kotlinx.coroutines issue #4073<\/a> calls that design error-prone. It was filed in March 2024. Our run with <code>catch (e: Exception)<\/code> spun 1.9 million times in a second.<\/p>\n\n<p>&#8220;Check whether the failure is a CancellationException and ignore it.&#8221; Ignoring it is still swallowing it. The loop keeps going. Our version of this answer ran a million empty passes in one second. The exception has to be thrown again for the job to end.<\/p>\n\n<p>&#8220;Run the poll on <code>Dispatchers.IO<\/code>.&#8221; The main thread comes free, so the freeze goes away. The loop does not. In our run it spun about half a million times a second on an IO thread. That burns CPU and battery until the process dies.<\/p>","protected":false},"excerpt":{"rendered":"<p>runCatching swallows CancellationException, so a cancelled polling loop spins and freezes the main thread. Runnable repro, the ensureActive fix, wrong answers.<\/p>\n","protected":false},"author":2,"featured_media":1088,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"rank_math_title":"runCatching Swallows CancellationException: Why a Kotlin Polling Loop Freezes the App After onCleared","rank_math_description":"runCatching swallows CancellationException, so a cancelled polling loop spins and freezes the main thread. Runnable repro, the ensureActive fix, wrong answers.","rank_math_focus_keyword":"runcatching swallows cancellationexception","footnotes":""},"categories":[9,3],"tags":[15,13,87,16,12,32,88,45],"class_list":["post-1087","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-bug-squash","category-coroutines","tag-android","tag-coroutines","tag-debugging-interview","tag-interview-prep","tag-kotlin","tag-lifecycle","tag-structured-concurrency","tag-technical-interview"],"_links":{"self":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts\/1087","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/comments?post=1087"}],"version-history":[{"count":1,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts\/1087\/revisions"}],"predecessor-version":[{"id":1089,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts\/1087\/revisions\/1089"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/media\/1088"}],"wp:attachment":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/media?parent=1087"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/categories?post=1087"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/tags?post=1087"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}