Custom error messages in Python - Time & Space Complexity
When we add custom error messages in code, it helps us understand problems better.
We want to see how adding these messages affects how long the program takes to run.
Analyze the time complexity of the following code snippet.
def divide_numbers(a, b):
if b == 0:
raise ValueError("Cannot divide by zero!")
return a / b
for i in range(1, 1000):
try:
result = divide_numbers(10, i - 500)
except ValueError as e:
print(e)
This code tries to divide 10 by numbers from -499 to 499, raising a custom error if dividing by zero.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop runs 999 times, calling the divide function each time.
- How many times: Exactly 999 times, once per loop iteration.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 calls to divide_numbers |
| 100 | About 100 calls to divide_numbers |
| 1000 | About 999 calls to divide_numbers |
Pattern observation: The number of operations grows directly with the input size; doubling input doubles work.
Time Complexity: O(n)
This means the time it takes grows in a straight line as the input size grows.
[X] Wrong: "Adding custom error messages makes the program much slower because of the extra text."
[OK] Correct: The error message text is just a small part and only runs when an error happens, so it does not change the overall growth with input size.
Understanding how error handling affects performance shows you can write clear and efficient code, a skill valued in real projects.
"What if we changed the loop to run inside another loop of the same size? How would the time complexity change?"