Finally block behavior in Kotlin - Time & Space Complexity
We want to understand how the time taken by a Kotlin program changes when it uses a finally block.
Specifically, we ask: does adding a finally block change how long the program runs as input grows?
Analyze the time complexity of the following code snippet.
fun processList(items: List<Int>) {
try {
for (item in items) {
println(item)
}
} finally {
println("Done processing")
}
}
This code prints each item in a list, then always prints "Done processing" at the end.
- Primary operation: The
forloop that prints each item in the list. - How many times: Once for each item in the list (n times).
- Finally block: Runs exactly once after the loop finishes.
The loop runs once per item, so if the list has more items, the time grows proportionally.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 prints + 1 finally print |
| 100 | About 100 prints + 1 finally print |
| 1000 | About 1000 prints + 1 finally print |
Pattern observation: The time grows roughly in a straight line with the number of items. The finally block adds a fixed small cost.
Time Complexity: O(n)
This means the time grows directly with the number of items; the finally block does not change this growth.
[X] Wrong: "The finally block runs multiple times and makes the program slower as the list grows."
[OK] Correct: The finally block runs only once after the loop, so it adds a fixed cost, not one per item.
Understanding how finally blocks behave helps you explain program flow clearly and reason about performance in real code.
What if the finally block contained a loop over the same list? How would the time complexity change?
Practice
What is the main purpose of the finally block in Kotlin?
Solution
Step 1: Understand the role of
Thefinallyfinallyblock runs aftertryandcatch, no matter what happens.Step 2: Identify its main use
It is used to run cleanup code like closing files or releasing resources, always executing even if exceptions occur.Final Answer:
To execute code that must run regardless of exceptions -> Option AQuick Check:
finallyalways runs = A [OK]
- Confusing finally with catch block
- Thinking finally only runs if no exception
- Believing finally stops program execution
Which of the following is the correct syntax for a try-catch-finally block in Kotlin?
?
Solution
Step 1: Recall Kotlin try-catch-finally order
The correct order istry, thencatch, thenfinally.Step 2: Check syntax correctness
try { /* code */ } catch (e: Exception) { /* handle */ } finally { /* cleanup */ } follows the correct order and syntax with exception type in catch.Final Answer:
try { /* code */ } catch (e: Exception) { /* handle */ } finally { /* cleanup */ } -> Option DQuick Check:
try-catch-finally order = C [OK]
- Placing finally before catch
- Omitting exception type in catch
- Starting with catch block
What will be the output of the following Kotlin code?
fun test(): Int {
try {
println("Try block")
return 1
} catch (e: Exception) {
println("Catch block")
return 2
} finally {
println("Finally block")
}
}
fun main() {
println("Result: ${test()}")
}Solution
Step 1: Trace the try block execution
The try block prints "Try block" and returns 1, but before returning, finally runs.Step 2: Understand finally block behavior with return
The finally block prints "Finally block" before the function returns the value 1.Final Answer:
Try block Finally block Result: 1 -> Option AQuick Check:
finally runs before return = A [OK]
- Ignoring finally output when return is in try
- Assuming catch runs without exception
- Thinking finally runs after return prints
Identify the error in this Kotlin code snippet:
fun example() {
try {
println("Inside try")
} finally {
println("Inside finally")
} catch (e: Exception) {
println("Inside catch")
}
}Solution
Step 1: Check order of try-catch-finally
The correct order is try, then catch, then finally. Here finally comes before catch, which is invalid.Step 2: Identify correct placement
The finally block must always come after all catch blocks.Final Answer:
"finally" block must come after "catch" block -> Option BQuick Check:
finally after catch = D [OK]
- Placing finally before catch
- Thinking catch can be after finally
- Ignoring syntax order rules
Consider this Kotlin function:
fun compute(): Int {
try {
return 10
} finally {
return 20
}
}What will compute() return and why?
Solution
Step 1: Analyze return in try block
The try block returns 10, but before returning, finally executes.Step 2: Understand return in finally block
The finally block also has a return statement, which overrides the previous return from try.Final Answer:
20, because finally's return overrides try's return -> Option CQuick Check:
Return in finally overrides try return = B [OK]
- Assuming first return always wins
- Thinking multiple returns cause error
- Ignoring finally's effect on return
Ready to prove it?
Pass the test and this pattern moves unknown
