RunCatching for safe execution in Kotlin - Time & Space Complexity
We want to understand how the time cost changes when using runCatching in Kotlin.
Specifically, how does wrapping code in runCatching affect the number of steps the program takes?
Analyze the time complexity of the following code snippet.
val result = runCatching {
val list = (1..n).toList()
list.map { it * 2 }
}
result.onSuccess { doubledList ->
println(doubledList)
}.onFailure {
println("Error occurred")
}
This code creates a list of numbers from 1 to n, doubles each number safely using runCatching, and prints the result or an error.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
mapfunction loops through the list of sizenonce. - How many times: Exactly
ntimes, once for each element.
As the input size n grows, the number of operations grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 map operations |
| 100 | About 100 map operations |
| 1000 | About 1000 map operations |
Pattern observation: Doubling the input roughly doubles the work done.
Time Complexity: O(n)
This means the time to run grows directly with the size of the list.
[X] Wrong: "Using runCatching adds extra loops or slows down the code a lot."
[OK] Correct: runCatching just wraps the code to catch errors; it does not add loops or repeat work. The main cost is still from the original operations like map.
Understanding how safe execution wrappers like runCatching affect performance shows you can write reliable code without losing track of efficiency.
"What if we replaced map with a nested loop inside runCatching? How would the time complexity change?"
Practice
runCatching in Kotlin?Solution
Step 1: Understand what
runCatchingdoesrunCatchingruns a block of code and catches any exceptions that happen inside it.Step 2: Identify the main purpose
This helps keep the program running smoothly by handling errors safely without crashing.Final Answer:
To execute code and catch exceptions safely without crashing the program -> Option AQuick Check:
runCatching = safe execution [OK]
- Thinking runCatching runs code conditionally
- Confusing runCatching with threading
- Assuming it converts types automatically
runCatching in Kotlin?Solution
Step 1: Recall the syntax of runCatching
runCatchingtakes a lambda block with curly braces to run code safely.Step 2: Match the correct syntax
val result = runCatching { someFunction() } uses curly braces and callssomeFunction()inside, which is correct.Final Answer:
val result = runCatching { someFunction() } -> Option CQuick Check:
runCatching uses braces { } [OK]
- Using parentheses instead of braces
- Trying to call runCatching like a function with arrow
- Accessing runCatching as an object
val result = runCatching { 10 / 0 }
println(result.isSuccess)Solution
Step 1: Analyze the code inside runCatching
The code tries to divide 10 by 0, which causes an exception (ArithmeticException).Step 2: Understand runCatching result
runCatching catches the exception, so no crash happens. TheisSuccessproperty will be false because the block failed.Final Answer:
false -> Option DQuick Check:
Exception caught means isSuccess = false [OK]
- Expecting true because code runs
- Thinking exception is thrown outside runCatching
- Confusing isSuccess with isFailure
runCatching:val result = runCatching {
val number = "abc".toInt()
}
println(result.getOrNull())Solution
Step 1: Understand the code inside runCatching
Trying to convert "abc" to Int causes NumberFormatException, but runCatching catches it.Step 2: Check what getOrNull() returns
Since exception happened,getOrNull()returns null safely without crashing.Final Answer:
No error, prints null because conversion fails -> Option AQuick Check:
Exception caught means getOrNull() = null [OK]
- Expecting exception to crash program
- Thinking getOrNull returns original string
- Assuming syntax error in code block
runCatching and collect only the successful results. Which Kotlin code snippet correctly does this?Solution
Step 1: Understand the goal
We want to convert strings to integers safely, ignoring failures, and collect only successful integers.Step 2: Analyze each option
val numbers = list.map { runCatching { it.toInt() }.getOrNull() }.filterNotNull() uses runCatching to catch exceptions, thengetOrNull()returns integer or null, andfilterNotNull()removes nulls, collecting only successful parses.Final Answer:
val numbers = list.map { runCatching { it.toInt() }.getOrNull() }.filterNotNull() -> Option BQuick Check:
Safe parse + filter null = val numbers = list.map { runCatching { it.toInt() }.getOrNull() }.filterNotNull() [OK]
- Using getOrThrow() which throws on failure
- Filtering nulls before catching exceptions
- Using exceptionOrNull() which returns exceptions, not values
Ready to prove it?
Pass the test and this pattern moves unknown
