Try–except–finally behavior in Python - Time & Space Complexity
We want to understand how the time a program takes changes when using try, except, and finally blocks.
Specifically, we ask: how does adding error handling affect the number of steps the program runs?
Analyze the time complexity of the following code snippet.
def process(items):
for item in items:
try:
print(item / 2)
except TypeError:
print("Not a number")
finally:
print("Done with item")
This code goes through a list, tries to divide each item by 2, handles errors if the item is not a number, and always prints a message after each item.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each item in the list.
- How many times: Once for each item in the input list.
Each item causes a fixed number of steps: try dividing, maybe catch an error, then print a message.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 30 steps (3 steps per item) |
| 100 | About 300 steps |
| 1000 | About 3000 steps |
Pattern observation: The total steps grow directly with the number of items. Double the items, double the steps.
Time Complexity: O(n)
This means the time grows in a straight line with the number of items processed.
[X] Wrong: "Try-except-finally blocks make the program much slower and change how time grows with input size."
[OK] Correct: The error handling adds a small fixed cost per item, but the overall time still grows linearly with the number of items.
Understanding how error handling affects performance helps you write clear and efficient code, a skill valued in real projects and interviews.
"What if the try block contained a nested loop over the items? How would the time complexity change?"