Generic exception handling in Python - Time & Space Complexity
When we use generic exception handling in Python, it can affect how long our program takes to run.
We want to see how the time to handle errors grows as the program runs.
Analyze the time complexity of the following code snippet.
try:
for i in range(n):
print(10 // i)
except Exception:
print("Error occurred")
This code tries to divide 10 by numbers from 0 to n-1 and catches any error that happens.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop runs from 0 to n-1.
- How many times: It repeats n times, but an exception may stop it early.
As n grows, the loop tries more divisions, but the first error stops the loop.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 1 operation before error (division by zero) |
| 100 | Still about 1 operation before error |
| 1000 | Still about 1 operation before error |
Pattern observation: The loop stops early due to the error, so operations do not grow with n.
Time Complexity: O(1)
This means the program runs in constant time because the error stops the loop quickly.
[X] Wrong: "The loop always runs n times even with exception handling."
[OK] Correct: The exception stops the loop early, so it does not always run fully.
Understanding how exceptions affect program flow and time helps you write better, more predictable code.
"What if the exception was handled inside the loop instead of outside? How would the time complexity change?"