Custom exception classes in Kotlin - Time & Space Complexity
When we create custom exception classes in Kotlin, we want to know how much time it takes to create and throw these exceptions.
We ask: How does the time to handle exceptions grow as we use them more?
Analyze the time complexity of the following code snippet.
class MyCustomException(message: String) : Exception(message)
fun checkValue(value: Int) {
if (value < 0) {
throw MyCustomException("Negative value not allowed")
}
}
fun processValues(values: List) {
for (v in values) {
checkValue(v)
}
}
This code defines a custom exception and throws it when a value is negative while processing a list of integers.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the list of values and checking each one.
- How many times: Once for each item in the list (n times).
As the list size grows, the number of checks grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to process values grows linearly with the number of values.
[X] Wrong: "Throwing a custom exception takes constant time no matter how many times it happens."
[OK] Correct: Each exception throw involves creating an object and stack trace work, so doing it many times adds up.
Understanding how exception handling scales helps you write code that stays efficient even when errors happen often.
"What if we changed the list to a sequence that processes items lazily? How would the time complexity change?"