Throw keyword in Java - Time & Space Complexity
Let's see how the throw keyword affects the time a program takes to run.
We want to know if throwing an exception changes how long the code runs as input grows.
Analyze the time complexity of the following code snippet.
public void checkNumber(int n) {
if (n < 0) {
throw new IllegalArgumentException("Negative number");
}
System.out.println("Number is " + n);
}
This code checks if a number is negative and throws an exception if it is.
Look for loops or repeated steps that take time as input grows.
- Primary operation: A simple if-check and possibly throwing an exception.
- How many times: The check happens once per call; no loops or recursion.
The time to run this code does not increase with the size of the input number.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 check, maybe 1 throw |
| 100 | 1 check, maybe 1 throw |
| 1000 | 1 check, maybe 1 throw |
Pattern observation: The number of steps stays the same no matter how big the number is.
Time Complexity: O(1)
This means the time to run the code stays constant, no matter the input size.
[X] Wrong: "Throwing an exception makes the program slower as input grows."
[OK] Correct: Throwing an exception happens instantly when the condition is met and does not depend on input size.
Understanding that throwing exceptions does not add loops or repeated work helps you explain code efficiency clearly and confidently.
"What if the code checked every element in a list and threw an exception on the first negative number? How would the time complexity change?"