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?"
Practice
Solution
Step 1: Understand what exceptions represent
Exceptions represent errors or unexpected events in a program.Step 2: Purpose of custom exceptions
Custom exceptions let you name specific error types clearly, making code easier to read and debug.Final Answer:
To define a specific type of error with a clear name -> Option BQuick Check:
Custom exceptions = clear error types [OK]
- Thinking custom exceptions fix errors automatically
- Believing they speed up code execution
- Confusing them with replacing built-in exceptions
MyError in Kotlin?Solution
Step 1: Recall Kotlin class declaration syntax
In Kotlin, classes are declared withclass ClassName.Step 2: Inherit from Exception class
Use colon:to inherit, soclass MyError : Exception()is correct.Final Answer:
class MyError : Exception() -> Option DQuick Check:
Custom exception syntax = class Name : Exception() [OK]
- Using 'fun' instead of 'class' to declare exception
- Using 'extends' or 'inherits' which are not Kotlin keywords
- Missing parentheses after Exception
class MyException : Exception("Custom error")
fun test() {
throw MyException()
}
fun main() {
try {
test()
} catch (e: MyException) {
println(e.message)
}
}Solution
Step 1: Understand the custom exception message
The class passes "Custom error" to Exception constructor, so e.message is "Custom error".Step 2: Catch block prints the exception message
The catch block catches MyException and prints e.message, which is "Custom error".Final Answer:
Custom error -> Option AQuick Check:
Exception message printed = Custom error [OK]
- Expecting class name instead of message
- Thinking program crashes without output
- Assuming message is null if not set explicitly
class MyException extends Exception() {}Solution
Step 1: Check Kotlin inheritance syntax
Kotlin uses colon ':' for inheritance, not 'extends'.Step 2: Identify the incorrect keyword
The code uses 'extends' which is from Java, causing syntax error.Final Answer:
Using 'extends' instead of ':' for inheritance -> Option CQuick Check:
Kotlin inheritance uses ':' not 'extends' [OK]
- Confusing Java syntax with Kotlin
- Thinking empty class body is invalid
- Believing Exception cannot be subclassed
InvalidAgeException that takes an age value as a property and shows a message like "Invalid age: 15". Which Kotlin code correctly implements this?Solution
Step 1: Understand primary constructor properties and string interpolation
In Kotlin,val param: Typecreates a read-only property accessible ase.age.Step 2: Constructor param available in super call
Params (with or without val) are in scope for superclass constructor, use$agefor interpolation (braces optional for simple identifiers).Step 3: Evaluate options
A correctly usesval age: Intfor property +$ageinterpolation. B/C/D lackval, so noageproperty (only private param). D uses concatenation (valid but less idiomatic).Final Answer:
class InvalidAgeException(val age: Int) : Exception("Invalid age: $age") -> Option AQuick Check:
val age: Int + $age interpolation for property + message [OK]
- Omitting 'val' (no public age property)
- Using unnecessary braces ${age} (optional for simple vars)
- Using string concatenation instead of interpolation
Ready to prove it?
Pass the test and this pattern moves unknown
