{"id":896,"date":"2026-10-25T13:57:00","date_gmt":"2026-10-25T12:57:00","guid":{"rendered":"https:\/\/grindloop.ai\/blog\/?p=896"},"modified":"2026-10-24T18:20:19","modified_gmt":"2026-10-24T16:20:19","slug":"withtimeout-timeoutcancellationexception-stuck-spinner","status":"publish","type":"post","link":"https:\/\/grindloop.ai\/blog\/withtimeout-timeoutcancellationexception-stuck-spinner\/","title":{"rendered":"Why withTimeout Never Crashes: TimeoutCancellationException and the Stuck Loading Spinner"},"content":{"rendered":"<p>A <code>withTimeout<\/code> that fires inside <code>viewModelScope.launch<\/code> throws <code>TimeoutCancellationException<\/code>. That class extends <code>CancellationException<\/code>. Coroutines treat a cancellation exception as a normal way to finish. So the launched coroutine ends as cancelled. Nothing crashes. No <code>CoroutineExceptionHandler<\/code> runs, so no crash reporter sees it. That is the first cause. The second sits in the screen&#8217;s own code. The <code>catch (e: IOException)<\/code> doesn&#8217;t match the timeout. So the line that clears the loading flag never runs. The spinner turns forever. The logs stay empty. The fix has two parts. First, turn the timeout into a value with <code>withTimeoutOrNull<\/code>. Then map <code>null<\/code> to an error state the user can see and retry from. Second, clear the loading flag in <code>finally<\/code>, so every exit path resets it. Don&#8217;t widen the catch to <code>Exception<\/code>. That also catches the normal cancel when the user leaves the screen.<\/p>\n\n<h2>A profile screen whose spinner never stops on a slow network<\/h2>\n\n<p>The running example is a profile screen. It shows a spinner, fetches the profile and shows the name. The ViewModel follows the shape of the login example on Android&#8217;s <a href=\"https:\/\/developer.android.com\/kotlin\/coroutines\/coroutines-best-practices\" target=\"_blank\" rel=\"noopener\">coroutines best practices page<\/a>. That page catches <code>IOException<\/code> inside <code>viewModelScope.launch<\/code>. A reviewer then asked for a five-second cap on the request. This is the change that shipped.<\/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=\"\">data class ProfileUiState(\n    val loading: Boolean = false,\n    val name: String? = null,\n    val error: String? = null,\n)\n\nclass ProfileViewModel(private val api: ProfileApi) : ViewModel() {\n    private val _state = MutableStateFlow(ProfileUiState())\n    val state: StateFlow&lt;ProfileUiState&gt; = _state\n\n    fun load() {\n        viewModelScope.launch {\n            _state.update { it.copy(loading = true, error = null) }\n            try {\n                val name = withTimeout(5.seconds) { api.fetchProfileName() }\n                _state.update { it.copy(loading = false, name = name) }\n            } catch (e: IOException) {\n                _state.update { it.copy(loading = false, error = \"Network error\") }\n            }\n        }\n    }\n}<\/pre>\n\n\n<p>On a fast network it works. On a slow one, the spinner never stops. Crashlytics shows nothing. Logcat has no stack trace. We ran the same code outside Android. A <code>CoroutineScope(SupervisorJob() + handler)<\/code> stood in for <code>viewModelScope<\/code>. The handler printed anything it received. The fake API took one second. The timeout was 200 ms.<\/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=\"\">job cancelled=true\nstate=ProfileUiState(loading=true, name=null, error=null)<\/pre>\n\n\n<p>The handler printed nothing. The job ended as cancelled. The state still said <code>loading=true<\/code>.<\/p>\n\n<h2>Cause one: TimeoutCancellationException is a cancellation, so nobody reports it<\/h2>\n\n<p>The <a href=\"https:\/\/kotlinlang.org\/api\/kotlinx.coroutines\/kotlinx-coroutines-core\/kotlinx.coroutines\/with-timeout.html\" target=\"_blank\" rel=\"noopener\"><code>withTimeout<\/code> API docs<\/a> say a timed-out block is cancelled with a <code>TimeoutCancellationException<\/code>. Their own example puts that call inside a <code>launch<\/code>. The surrounding <code>coroutineScope<\/code> still finishes normally. The docs give the reason. A coroutine that ends with a <code>CancellationException<\/code> doesn&#8217;t pass the error to its parent.<\/p>\n\n<p>The <a href=\"https:\/\/kotlinlang.org\/docs\/exception-handling.html\" target=\"_blank\" rel=\"noopener\">coroutine exception handling guide<\/a> goes one step further. It says cancellation exceptions &#8220;are ignored by all handlers&#8221;. So the timeout never reaches a <code>CoroutineExceptionHandler<\/code>. It never reaches the thread&#8217;s uncaught exception handler either. No crash means no crash report. Our repro confirmed it. The handler stayed silent through the timeout.<\/p>\n\n<p>The maintainers know this trap. <a href=\"https:\/\/github.com\/Kotlin\/kotlinx.coroutines\/issues\/1374\" target=\"_blank\" rel=\"noopener\">kotlinx.coroutines issue #1374<\/a> was filed by a maintainer in July 2019. It shows this exact <code>launch<\/code> plus <code>withTimeout<\/code> shape and calls it a source of subtle errors. It proposes replacing the class with a <code>TimeoutException<\/code> that isn&#8217;t a cancellation. The issue is still open. So the behavior holds in current releases, including the 1.10.2 we ran.<\/p>\n\n<h2>Cause two: the loading flag is reset only on paths the timeout never takes<\/h2>\n\n<p>Cause one explains the missing crash. It doesn&#8217;t explain the stuck spinner. That comes from where the ViewModel clears <code>loading<\/code>. The flag goes back to <code>false<\/code> in two places. One is the success line after <code>withTimeout<\/code>. The other is the <code>IOException<\/code> catch.<\/p>\n\n<p>The timeout takes neither path. <code>withTimeout<\/code> throws, so the success line is skipped. <code>TimeoutCancellationException<\/code> isn&#8217;t an <code>IOException<\/code>, so the catch doesn&#8217;t match. The exception leaves the <code>launch<\/code> body. Then the coroutine ends. The last state written was <code>loading = true<\/code>.<\/p>\n\n<p>Either cause alone would be easy to spot. If the timeout crashed, Crashlytics would show a stack trace pointing at the call. If the catch matched, the flag would reset. Together, they leave no trace except a spinner on the user&#8217;s screen.<\/p>\n\n<h2>The fix: make the timeout a value and reset the flag in finally<\/h2>\n\n<p>The <code>withTimeout<\/code> docs suggest <code>withTimeoutOrNull<\/code> when a timeout should count as a real error. It returns <code>null<\/code> on timeout instead of throwing. The ViewModel can then turn <code>null<\/code> into an error state. The loading reset moves to <code>finally<\/code>, so it runs on every exit.<\/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=\"\">fun load() {\n    viewModelScope.launch {\n        _state.update { it.copy(loading = true, error = null) }\n        try {\n            val name = withTimeoutOrNull(5.seconds) { api.fetchProfileName() }\n            if (name == null) {\n                Log.w(TAG, \"Profile fetch timed out\")\n                _state.update { it.copy(error = \"Taking too long. Try again.\") }\n            } else {\n                _state.update { it.copy(name = name) }\n            }\n        } catch (e: IOException) {\n            _state.update { it.copy(error = \"Network error\") }\n        } finally {\n            _state.update { it.copy(loading = false) }\n        }\n    }\n}<\/pre>\n\n\n<p>We ran this version against four fake backends. The slow API ended with <code>loading=false<\/code> and the &#8220;Taking too long&#8221; error. The fast API ended with the name set. The failing API ended with &#8220;Network error&#8221;. For the fourth case we cancelled the scope mid-fetch, the way <code>onCleared()<\/code> does. The job ended as cancelled with no error message. That is the correct result. The <code>finally<\/code> still cleared the flag.<\/p>\n\n<p><code>withTimeoutOrNull<\/code> can&#8217;t tell a timeout from a block that returns <code>null<\/code>. In our run, a block that returned <code>null<\/code> after 10 ms gave the same <code>null<\/code> as a timeout. If <code>fetchProfileName()<\/code> can return <code>null<\/code>, catch the timeout right at the call instead.<\/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=\"\">val name: String? = try {\n    withTimeout(5.seconds) { api.fetchProfileName() }\n} catch (e: TimeoutCancellationException) {\n    throw ProfileTimeoutException(e) \/\/ a plain Exception subclass, not a cancellation\n}<\/pre>\n\n\n<p>Catching this one class is safe. When the outer scope is cancelled, <code>withTimeout<\/code> throws a <code>JobCancellationException<\/code> instead. Our repro showed that exception passing straight by a <code>TimeoutCancellationException<\/code> catch. After a caught timeout, the coroutine itself stays active. Our run printed <code>isActive=true<\/code> and kept suspending normally. The ViewModel then catches <code>ProfileTimeoutException<\/code> next to <code>IOException<\/code>. If nothing catches it, it now reaches the handler. Our run printed it there, unlike the original timeout.<\/p>\n\n<h2>What to tell the interviewer when they ask why nothing crashed<\/h2>\n\n<p>This bug fits a live debugging round well. The interviewer shows the ViewModel and says the spinner sticks on slow networks. Our post on <a href=\"https:\/\/grindloop.ai\/blog\/android-debugging-interview-second-bug\/\">how the Android debugging round is scored<\/a> covers the format. A strong answer runs in this order.<\/p>\n\n<ol>\n<li>Name the class. <code>withTimeout<\/code> throws <code>TimeoutCancellationException<\/code>. That class is a <code>CancellationException<\/code>.<\/li>\n<li>Say what that means. The <code>launch<\/code> ends as cancelled. Handlers ignore cancellation, so there&#8217;s no crash and no report.<\/li>\n<li>Trace the state. The success line and the <code>IOException<\/code> catch both reset <code>loading<\/code>. The timeout takes neither, so <code>loading<\/code> stays <code>true<\/code>.<\/li>\n<li>Give the fix. Use <code>withTimeoutOrNull<\/code> and map <code>null<\/code> to an error. Move the reset to <code>finally<\/code>.<\/li>\n<li>Name the limit. If the call can return <code>null<\/code>, catch <code>TimeoutCancellationException<\/code> at the call and rethrow a normal exception.<\/li>\n<li>Defend the catch. Don&#8217;t catch <code>Exception<\/code>. Leaving the screen throws a cancellation too. That one must pass through.<\/li>\n<\/ol>\n\n<p>Point 6 rules out the shortcut most likely to come up next. Android&#8217;s best practices page says not to consume <code>CancellationException<\/code>. It also says to catch specific types over <code>Exception<\/code>. Our earlier posts show the same rule breaking <a href=\"https:\/\/grindloop.ai\/blog\/viewmodelscope-async-swallows-api-call\/\">an unawaited async<\/a> and <a href=\"https:\/\/grindloop.ai\/blog\/viewmodelscope-launch-supervisorjob-crash\/\">a SupervisorJob passed to launch<\/a>.<\/p>\n\n<h2>Answers that hide the spinner but keep a second bug<\/h2>\n\n<ul>\n<li>&#8220;Add a <code>CoroutineExceptionHandler<\/code> to the scope.&#8221; Our repro had one installed. It printed nothing, because handlers ignore cancellation exceptions.<\/li>\n<li>&#8220;Change the catch to <code>catch (e: Exception)<\/code>.&#8221; It catches the timeout. It also catches the <code>JobCancellationException<\/code> from leaving the screen. In our run, that broad catch fired after a plain scope cancel. The screen would show a network error for a user who just pressed back.<\/li>\n<li>&#8220;Catch <code>CancellationException<\/code> and set the error there.&#8221; A real cancel and a timeout both land in that block. Android&#8217;s guide says to rethrow a caught <code>CancellationException<\/code>.<\/li>\n<li>&#8220;Only move <code>loading = false<\/code> into <code>finally<\/code>.&#8221; The spinner stops. But the user sees a blank profile with no error. Nothing gets logged either. That fixes cause two and leaves cause one.<\/li>\n<li>&#8220;<code>withTimeout<\/code> stops the request at five seconds no matter what.&#8221; Cancellation is cooperative, as Android&#8217;s guide says. A blocking call with no suspension point keeps running past the deadline.<\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>TimeoutCancellationException is a cancellation, so withTimeout in launch never crashes or logs. An IOException catch leaves the spinner stuck. Repro and fix.<\/p>\n","protected":false},"author":2,"featured_media":898,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"rank_math_title":"Why withTimeout Never Crashes: TimeoutCancellationException and the Stuck Loading Spinner","rank_math_description":"TimeoutCancellationException is a cancellation, so withTimeout in launch never crashes or logs. An IOException catch leaves the spinner stuck. Repro and fix.","rank_math_focus_keyword":"timeoutcancellationexception","footnotes":""},"categories":[9,3],"tags":[15,13,87,16,12,88,45],"class_list":["post-896","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-structured-concurrency","tag-technical-interview"],"_links":{"self":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts\/896","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=896"}],"version-history":[{"count":1,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts\/896\/revisions"}],"predecessor-version":[{"id":897,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts\/896\/revisions\/897"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/media\/898"}],"wp:attachment":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/media?parent=896"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/categories?post=896"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/tags?post=896"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}