Exception chaining in Python - Time & Space Complexity
When using exception chaining in Python, it's important to understand how the program's steps grow as errors happen.
We want to see how the handling of exceptions affects the number of operations as the program runs.
Analyze the time complexity of the following code snippet.
def process(data):
try:
result = 10 / data
except ZeroDivisionError as e:
raise ValueError("Invalid input") from e
return result
for i in range(5):
try:
print(process(i - 2))
except ValueError as err:
print(err)
This code tries to divide 10 by a number, catches division errors, and chains exceptions to give clearer messages.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop runs 5 times, calling the process function each time.
- How many times: The division and exception handling happen once per loop iteration.
Each loop iteration does a fixed amount of work: one division and possibly one exception chain.
| Input Size (n) | Approx. Operations |
|---|---|
| 5 | 5 divisions and up to 5 exception checks |
| 10 | 10 divisions and up to 10 exception checks |
| 100 | 100 divisions and up to 100 exception checks |
Pattern observation: The total steps grow directly with the number of inputs; doubling inputs doubles work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of inputs processed.
[X] Wrong: "Exception chaining adds a lot of extra time and makes the program slow in a complex way."
[OK] Correct: Exception chaining only adds a small fixed cost per exception; it does not change how the program scales with input size.
Understanding how exception handling affects program steps helps you write clear, efficient code and explain your reasoning confidently.
"What if the process function called itself recursively on error? How would the time complexity change?"