Why withTimeout Never Crashes: TimeoutCancellationException and the Stuck Loading Spinner

A withTimeout that fires inside viewModelScope.launch throws TimeoutCancellationException. That class extends CancellationException. Coroutines treat a cancellation exception as a normal way to finish. So the launched coroutine ends as cancelled. Nothing crashes. No CoroutineExceptionHandler runs, so no crash reporter sees it. That is the first cause. The second sits in the screen’s own code. The catch (e: IOException) doesn’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 withTimeoutOrNull. Then map null to an error state the user can see and retry from. Second, clear the loading flag in finally, so every exit path resets it. Don’t widen the catch to Exception. That also catches the normal cancel when the user leaves the screen.

A profile screen whose spinner never stops on a slow network

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’s coroutines best practices page. That page catches IOException inside viewModelScope.launch. A reviewer then asked for a five-second cap on the request. This is the change that shipped.

data class ProfileUiState(
    val loading: Boolean = false,
    val name: String? = null,
    val error: String? = null,
)

class ProfileViewModel(private val api: ProfileApi) : ViewModel() {
    private val _state = MutableStateFlow(ProfileUiState())
    val state: StateFlow<ProfileUiState> = _state

    fun load() {
        viewModelScope.launch {
            _state.update { it.copy(loading = true, error = null) }
            try {
                val name = withTimeout(5.seconds) { api.fetchProfileName() }
                _state.update { it.copy(loading = false, name = name) }
            } catch (e: IOException) {
                _state.update { it.copy(loading = false, error = "Network error") }
            }
        }
    }
}

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 CoroutineScope(SupervisorJob() + handler) stood in for viewModelScope. The handler printed anything it received. The fake API took one second. The timeout was 200 ms.

job cancelled=true
state=ProfileUiState(loading=true, name=null, error=null)

The handler printed nothing. The job ended as cancelled. The state still said loading=true.

Cause one: TimeoutCancellationException is a cancellation, so nobody reports it

The withTimeout API docs say a timed-out block is cancelled with a TimeoutCancellationException. Their own example puts that call inside a launch. The surrounding coroutineScope still finishes normally. The docs give the reason. A coroutine that ends with a CancellationException doesn’t pass the error to its parent.

The coroutine exception handling guide goes one step further. It says cancellation exceptions “are ignored by all handlers”. So the timeout never reaches a CoroutineExceptionHandler. It never reaches the thread’s uncaught exception handler either. No crash means no crash report. Our repro confirmed it. The handler stayed silent through the timeout.

The maintainers know this trap. kotlinx.coroutines issue #1374 was filed by a maintainer in July 2019. It shows this exact launch plus withTimeout shape and calls it a source of subtle errors. It proposes replacing the class with a TimeoutException that isn’t a cancellation. The issue is still open. So the behavior holds in current releases, including the 1.10.2 we ran.

Cause two: the loading flag is reset only on paths the timeout never takes

Cause one explains the missing crash. It doesn’t explain the stuck spinner. That comes from where the ViewModel clears loading. The flag goes back to false in two places. One is the success line after withTimeout. The other is the IOException catch.

The timeout takes neither path. withTimeout throws, so the success line is skipped. TimeoutCancellationException isn’t an IOException, so the catch doesn’t match. The exception leaves the launch body. Then the coroutine ends. The last state written was loading = true.

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’s screen.

The fix: make the timeout a value and reset the flag in finally

The withTimeout docs suggest withTimeoutOrNull when a timeout should count as a real error. It returns null on timeout instead of throwing. The ViewModel can then turn null into an error state. The loading reset moves to finally, so it runs on every exit.

fun load() {
    viewModelScope.launch {
        _state.update { it.copy(loading = true, error = null) }
        try {
            val name = withTimeoutOrNull(5.seconds) { api.fetchProfileName() }
            if (name == null) {
                Log.w(TAG, "Profile fetch timed out")
                _state.update { it.copy(error = "Taking too long. Try again.") }
            } else {
                _state.update { it.copy(name = name) }
            }
        } catch (e: IOException) {
            _state.update { it.copy(error = "Network error") }
        } finally {
            _state.update { it.copy(loading = false) }
        }
    }
}

We ran this version against four fake backends. The slow API ended with loading=false and the “Taking too long” error. The fast API ended with the name set. The failing API ended with “Network error”. For the fourth case we cancelled the scope mid-fetch, the way onCleared() does. The job ended as cancelled with no error message. That is the correct result. The finally still cleared the flag.

withTimeoutOrNull can’t tell a timeout from a block that returns null. In our run, a block that returned null after 10 ms gave the same null as a timeout. If fetchProfileName() can return null, catch the timeout right at the call instead.

val name: String? = try {
    withTimeout(5.seconds) { api.fetchProfileName() }
} catch (e: TimeoutCancellationException) {
    throw ProfileTimeoutException(e) // a plain Exception subclass, not a cancellation
}

Catching this one class is safe. When the outer scope is cancelled, withTimeout throws a JobCancellationException instead. Our repro showed that exception passing straight by a TimeoutCancellationException catch. After a caught timeout, the coroutine itself stays active. Our run printed isActive=true and kept suspending normally. The ViewModel then catches ProfileTimeoutException next to IOException. If nothing catches it, it now reaches the handler. Our run printed it there, unlike the original timeout.

What to tell the interviewer when they ask why nothing crashed

This bug fits a live debugging round well. The interviewer shows the ViewModel and says the spinner sticks on slow networks. Our post on how the Android debugging round is scored covers the format. A strong answer runs in this order.

  1. Name the class. withTimeout throws TimeoutCancellationException. That class is a CancellationException.
  2. Say what that means. The launch ends as cancelled. Handlers ignore cancellation, so there’s no crash and no report.
  3. Trace the state. The success line and the IOException catch both reset loading. The timeout takes neither, so loading stays true.
  4. Give the fix. Use withTimeoutOrNull and map null to an error. Move the reset to finally.
  5. Name the limit. If the call can return null, catch TimeoutCancellationException at the call and rethrow a normal exception.
  6. Defend the catch. Don’t catch Exception. Leaving the screen throws a cancellation too. That one must pass through.

Point 6 rules out the shortcut most likely to come up next. Android’s best practices page says not to consume CancellationException. It also says to catch specific types over Exception. Our earlier posts show the same rule breaking an unawaited async and a SupervisorJob passed to launch.

Answers that hide the spinner but keep a second bug

  • “Add a CoroutineExceptionHandler to the scope.” Our repro had one installed. It printed nothing, because handlers ignore cancellation exceptions.
  • “Change the catch to catch (e: Exception).” It catches the timeout. It also catches the JobCancellationException 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.
  • “Catch CancellationException and set the error there.” A real cancel and a timeout both land in that block. Android’s guide says to rethrow a caught CancellationException.
  • “Only move loading = false into finally.” 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.
  • “withTimeout stops the request at five seconds no matter what.” Cancellation is cooperative, as Android’s guide says. A blocking call with no suspension point keeps running past the deadline.

Leave a Comment