This program tries to do 5 tasks, each taking 300ms. The total time is 1500ms, but the timeout is 1000ms, so it stops early and prints a timeout message.
Kotlin
import kotlinx.coroutines.*
fun main() = runBlocking {
try {
withTimeout(1000) {
repeat(5) { i ->
println("Working on task $i...")
delay(300) // simulate work
}
}
} catch (e: TimeoutCancellationException) {
println("Task timed out!")
}
}
OutputSuccess
Important Notes
Use withTimeout inside a coroutine or suspend function.
The timeout exception can be caught to handle the timeout gracefully.
Use withTimeoutOrNull if you want to get null instead of an exception on timeout.
Summary
withTimeout stops a block if it runs too long.
It throws an exception you can catch to handle timeouts.
Great for keeping your app responsive and avoiding long waits.
Practice
(1/5)
1. What does the Kotlin function withTimeout do?
easy
A. It cancels all running coroutines immediately.
B. It repeats a block of code until a timeout occurs.
C. It stops a block of code if it runs longer than the specified time.
D. It delays the execution of a block for a fixed time.
Solution
Step 1: Understand the purpose of withTimeout
withTimeout is designed to stop a block of code if it exceeds a given time limit.
Step 2: Compare options with the definition
Only "It stops a block of code if it runs longer than the specified time." correctly describes this behavior. Other options describe different coroutine behaviors.
Final Answer:
It stops a block of code if it runs longer than the specified time. -> Option C
A. TimeoutCancellationException is thrown because delay exceeds timeout.
B. Syntax error: withTimeout requires a try-catch block.
C. No error; code runs and prints "Done" after 200ms.
D. Delay function cannot be used inside withTimeout.
Solution
Step 1: Understand withTimeout behavior with delay
The delay of 200ms exceeds the 100ms timeout, causing a TimeoutCancellationException.
Step 2: Check error handling
No try-catch is present, so exception will be thrown and program will crash.
Final Answer:
TimeoutCancellationException is thrown because delay exceeds timeout. -> Option A
Quick Check:
Delay longer than timeout causes exception [OK]
Hint: Delay longer than timeout causes exception unless caught [OK]
Common Mistakes:
Assuming code waits full delay then prints
Thinking try-catch is mandatory syntax
Believing delay can't be used inside withTimeout
5. You want to run a network request that should timeout after 500ms. Which Kotlin code correctly uses withTimeout to achieve this and handle timeout gracefully?