Try-catch as an expression in Kotlin - Time & Space Complexity
We want to understand how the time needed to run a try-catch expression changes as the input or operations inside it grow.
Specifically, we ask: how does using try-catch as an expression affect the program's running time?
Analyze the time complexity of the following code snippet.
fun parseNumber(input: String): Int = try {
input.toInt()
} catch (e: NumberFormatException) {
-1
}
fun processList(inputs: List): List {
return inputs.map { parseNumber(it) }
}
This code tries to convert each string in a list to an integer using try-catch as an expression.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The map function loops over each element in the input list.
- How many times: Once for each string in the list (n times if list size is n).
Each input string is processed once, so the total work grows directly with the number of inputs.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 conversions and try-catch checks |
| 100 | About 100 conversions and try-catch checks |
| 1000 | About 1000 conversions and try-catch checks |
Pattern observation: The work increases evenly as the list size grows.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of input strings.
[X] Wrong: "Try-catch blocks always make the code run slower by a lot."
[OK] Correct: The try-catch expression itself does not add repeated overhead; it only handles exceptions when they happen. Normal execution without exceptions runs almost as fast as code without try-catch.
Understanding how try-catch as an expression affects time helps you write clear and efficient Kotlin code, a skill valued in many coding challenges and real projects.
What if the parseNumber function threw exceptions for most inputs? How would that affect the time complexity?
Practice
try-catch is an expression in Kotlin?Solution
Step 1: Understand try-catch as an expression
In Kotlin,try-catchcan produce a value, unlike in some languages where it is only a statement.Step 2: Recognize value assignment
This means you can assign the result of atry-catchblock directly to a variable.Final Answer:
It can return a value that can be assigned to a variable. -> Option DQuick Check:
Try-catch returns value = D [OK]
- Thinking try-catch cannot return values
- Confusing try-catch with only statements
- Believing finally is always required
Solution
Step 1: Check assignment syntax
The correct way to assign a value from try-catch is usingval result = try { ... } catch { ... }.Step 2: Validate each option
val result = try { 10 / 0 } catch (e: Exception) { 0 } uses correct syntax with try-catch returning a value. Options A, B, and D have syntax errors or misuse of finally/catch.Final Answer:
val result = try { 10 / 0 } catch (e: Exception) { 0 } -> Option AQuick Check:
Correct try-catch assignment syntax = C [OK]
- Omitting '=' in assignment
- Using finally block to return value
- Placing catch before try
val result = try {
val num = 10 / 2
"Success: $num"
} catch (e: Exception) {
"Error"
}
println(result)Solution
Step 1: Evaluate try block
The division 10 / 2 equals 5, so the try block returns the string "Success: 5".Step 2: Check for exceptions
No exception occurs, so the catch block is skipped.Final Answer:
Success: 5 -> Option BQuick Check:
Try succeeds, output = Success: 5 [OK]
- Assuming catch runs even without error
- Printing the expression instead of result
- Confusing integer division with string output
val result = try {
val x = 10 / 0
x
} catch {
0
}
println(result)Solution
Step 1: Check catch block syntax
The catch block must declare an exception parameter likecatch (e: Exception).Step 2: Identify the error
Here, catch is missing the exception parameter, causing a syntax error.Final Answer:
Missing exception parameter in catch block -> Option CQuick Check:
Catch needs exception parameter = B [OK]
- Omitting exception parameter in catch
- Ignoring division by zero error
- Thinking try-catch can't be assigned
parseIntOrZero("abc") return?fun parseIntOrZero(input: String): Int = try {
input.toInt()
} catch (e: NumberFormatException) {
0
}Solution
Step 1: Analyze try block behavior
Callinginput.toInt()on "abc" throwsNumberFormatException.Step 2: Catch block returns fallback
The catch block catches this exception and returns 0 as fallback.Final Answer:
Returns 0 -> Option AQuick Check:
Exception caught, fallback 0 returned = A [OK]
- Expecting exception to propagate
- Thinking null is returned on error
- Confusing return type with input type
Ready to prove it?
Pass the test and this pattern moves unknown
