Raising exceptions in Python - Time & Space Complexity
When we raise exceptions in Python, it's important to know how this affects the program's speed as the input grows.
We want to see how the time to raise an exception changes when the program runs.
Analyze the time complexity of the following code snippet.
def check_positive(numbers):
for num in numbers:
if num < 0:
raise ValueError(f"Negative number found: {num}")
return True
This code checks a list of numbers and raises an exception if it finds any negative number.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the list.
- How many times: Up to once per number until a negative is found or the list ends.
As the list gets bigger, the program checks more numbers until it finds a negative or finishes.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
| 1000 | Up to 1000 checks |
Pattern observation: The number of checks grows directly with the list size until an exception stops it.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of items checked before raising an exception or finishing.
[X] Wrong: "Raising an exception takes constant time no matter where it happens."
[OK] Correct: Actually, the time depends on when the exception is raised during the loop. If it's early, fewer checks happen; if late or never, more checks happen.
Understanding how raising exceptions affects time helps you explain program behavior clearly and shows you think about efficiency in real situations.
"What if we changed the code to collect all negative numbers before raising an exception? How would the time complexity change?"