withTimeout vs withTimeoutOrNull

Coroutines Junior Kotlin 2.0+ API 24+ Reviewed By Best Latest Apps

Predict the output

What does this print?

fun main() = runBlocking {
    val result = withTimeoutOrNull(300) {
        delay(1_000)
        "loaded"
    }
    println(result ?: "timed out")
}
Options
Hint 1 of 1

Which is longer: the delay or the timeout?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A timed out

Correct. The block is cancelled at 300 ms and withTimeoutOrNull returns null.

Why not the others?
  • B loaded. The delay is longer than the timeout.
  • C It throws TimeoutCancellationException. That's withTimeout; the OrNull version returns null.
  • D It prints nothing and hangs. delay is cancellable, so the timeout ends it.

30-second answer

withTimeout(ms) { } cancels the block when the time runs out and throws TimeoutCancellationException. withTimeoutOrNull returns null instead of throwing, which is usually easier to handle. Both rely on cancellation, so a block that blocks the thread without suspending will overrun the timeout.

Practise saying it · 30 s. No recording, just a timer

Explain timeouts in coroutines.

Say your answer out loud, then check which of these points you covered:

  • withTimeout throws, OrNull returns null
  • Built on cancellation
  • Blocking code overruns it
  • Release resources in finally

Deep dive

The exception is a subclass of CancellationException, so a broad catch around it can swallow it silently.

Throwing from withTimeout inside a launch without a catch cancels the coroutine quietly rather than crashing, because it is a cancellation.

Resources acquired inside the block should be released in finally, because the block can be cut off at any suspension point.

OkHttp also has its own call timeouts; use them for network calls, and coroutine timeouts for multi-step deadlines.

Common mistakes

  • Using withTimeout and catching Exception, which also hides the timeout from callers.
  • Expecting it to stop Thread.sleep or blocking I/O.
  • Returning a resource from inside the block without handling a timeout race.

Senior take & follow-ups

Mention that it's built on cancellation and why that matters: a non-cooperative block ignores it.

Follow-up questions

Think of your answer first, then open the hint.

  1. What does withTimeoutOrNull return on success?

    Show hint

    The block's value.

  2. Why might a timeout not fire on time?

    Show hint

    The block doesn't suspend, so cancellation isn't noticed.

Suggest a fix if something here is wrong or out of date.