Handling specific exceptions in Python - Time & Space Complexity
When we handle specific exceptions in Python, we want to know how the program's running time changes as the input grows.
We ask: How does catching errors affect how long the program takes?
Analyze the time complexity of the following code snippet.
def divide_numbers(numbers, divisor):
results = []
for num in numbers:
try:
results.append(num / divisor)
except ZeroDivisionError:
results.append(None)
return results
This code divides each number in a list by a divisor, handling the case when the divisor is zero.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the list.
- How many times: Once for every item in the input list.
As the list gets bigger, the program does more divisions and checks for exceptions.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 divisions and checks |
| 100 | About 100 divisions and checks |
| 1000 | About 1000 divisions and checks |
Pattern observation: The work grows directly with the number of items in the list.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the list size.
[X] Wrong: "Handling exceptions inside the loop makes the program much slower and changes the time complexity."
[OK] Correct: The exception handling adds a small fixed cost per item, but the main time still grows linearly with the list size.
Understanding how exception handling affects time helps you write clear and efficient code, a skill valued in real projects and interviews.
"What if we moved the try-except block outside the loop? How would the time complexity change?"