What do withTimeout and withTimeoutOrNull do in Kotlin coroutines, and how do they differ?
answer
- withTimeout throws, withTimeoutOrNull returns null
- TimeoutCancellationException is a CancellationException
- Cancellation is cooperative — needs a suspension point
- Both take Duration or Long millis
- On success both return the block's value
basics
~10 sBoth run a block of code with a time limit. If the work takes too long, withTimeout throws an error, while withTimeoutOrNull just returns null. Use them so slow operations don't hang forever.
solid answer
~40 sBoth are suspend functions that bound the execution time of a coroutine block. `withTimeout(duration) { ... }` runs the block; if it doesn't finish within the duration, it cancels the block and throws `TimeoutCancellationException` (a subclass of `CancellationException`). `withTimeoutOrNull(duration) { ... }` does the same cancellation but swallows the timeout and returns `null` instead of throwing; on success it returns the block's result. Both accept either a `kotlin.time.Duration` (e.g. `5.seconds`) or a `Long` milliseconds overload. The timeout only fires at a suspension point because cancellation is cooperative — a tight non-suspending loop won't be interrupted. Prefer `withTimeoutOrNull` when a timeout is an expected, recoverable outcome; prefer `withTimeout` when exceeding the deadline is an error worth propagating.
code
kotlin · 10 linesimport kotlinx.coroutines.*
import kotlin.time.Duration.Companion.seconds
suspend fun load(): String {
val result = withTimeoutOrNull(1.seconds) {
delay(3.seconds)
"loaded"
}
return result ?: "timed out"
}go deeper
Knows withTimeout throws and withTimeoutOrNull returns null, and that both bound execution time.
Explains TimeoutCancellationException as a CancellationException and chooses the right variant per situation.
Ties behavior to cooperative cancellation and suspension points; warns about swallowing CancellationException.
Frames timeouts as a reliability/back-pressure concern across call chains and library boundaries, with consistent policy.
## What these functions are `withTimeout` and `withTimeoutOrNull` are `suspend` functions from `kotlinx.coroutines` that run a block of suspending code under a deadline. They create a child coroutine scope and start a timer; if the block hasn't completed when the timer expires, the child is **cancelled**. - **`withTimeout(timeout) { block }`** — returns the block's result if it finishes in time; otherwise throws `TimeoutCancellationException`. - **`withTimeoutOrNull(timeout) { block }`** — returns the block's result if it finishes in time; otherwise returns `null`. Both have two overloads: one taking a `kotlin.time.Duration` and one taking `timeMillis: Long`. ```kotlin import kotlinx.coroutines.* import kotlin.time.Duration.Companion.seconds suspend fun fetch(): String { return withTimeoutOrNull(2.seconds) { delay(5.seconds) // suspension point — cancellable "data" } ?: "fallback" // null when it times out } ``` ## TimeoutCancellationException `TimeoutCancellationException` extends `CancellationException`. This matters: `CancellationException` is treated specially by the coroutine machinery — it signals normal cancellation and is **not** propagated to a parent as a failure. `withTimeoutOrNull` works precisely because it catches *its own* `TimeoutCancellationException` and converts it to `null`. A broad `catch (e: Exception)` inside the block can accidentally swallow this exception and break cancellation — always rethrow `CancellationException`. ## Cooperative cancellation The timeout does not forcibly stop a thread. It cancels the coroutine, which only takes effect at a **suspension point** (any `suspend` call like `delay`, network I/O, `yield`) or where code checks `isActive`/`ensureActive`. A CPU-bound loop with no suspension ignores the deadline: ```kotlin withTimeout(100) { var i = 0L while (i < Long.MAX_VALUE) i++ // never cancelled — no suspension point } ``` ## Which to choose - Use `withTimeout` when blowing the deadline is an error you want to surface or log. - Use `withTimeoutOrNull` when a timeout is an expected outcome you handle inline (e.g. show a fallback).
- Does the timeout interrupt a tight non-suspending loop?No. Cancellation is cooperative, so it only takes effect at a suspension point or an isActive/ensureActive check. A pure CPU loop with no suspension keeps running past the deadline.
- What type of exception does withTimeout throw?TimeoutCancellationException, which is a subclass of CancellationException.
A kitchen timer: withTimeout rings an alarm (throws) when time's up; withTimeoutOrNull just quietly hands you an empty plate (null).
saying these in an interview costs you the question
- Saying withTimeoutOrNull throws an exception
- Claiming the timeout forcibly kills the thread
- Thinking a CPU-bound loop gets cancelled at the deadline
- Not knowing it returns the block's result on success
- Confusing it with a blocking Thread.sleep-based timer