Best practices for custom exceptions in Python - Time & Space Complexity
When creating custom exceptions in Python, it is important to understand how the code that raises and handles these exceptions behaves as the program grows.
We want to know how the time cost changes when exceptions are used in different ways.
Analyze the time complexity of raising and catching a custom exception in this code.
class MyError(Exception):
pass
def check_value(x):
if x < 0:
raise MyError("Negative value")
return x
try:
result = check_value(-1)
except MyError as e:
print(e)
This code defines a custom exception and raises it when a negative value is passed, then catches and prints the error message.
Look for operations that repeat or dominate time cost.
- Primary operation: Raising and catching the custom exception.
- How many times: Once per call that triggers the exception.
Raising an exception is a fixed cost operation each time it happens, independent of input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks, exceptions raised only if negative values found |
| 100 | 100 checks, exceptions raised only if negative values found |
| 1000 | 1000 checks, exceptions raised only if negative values found |
Pattern observation: The cost grows linearly with the number of checks, but the exception handling cost only occurs when an exception is raised.
Time Complexity: O(n)
This means the time grows linearly with the number of inputs checked, but raising exceptions is a rare, fixed cost per occurrence.
[X] Wrong: "Raising exceptions is always slow and should be avoided at all costs."
[OK] Correct: Exceptions only cost extra time when raised, not when code runs normally. Using them properly for rare errors is fine and does not slow down normal execution.
Understanding how exceptions affect time helps you write clear, efficient code that handles errors well. This skill shows you can balance correctness and performance.
"What if we changed the code to catch exceptions inside a loop that runs many times? How would the time complexity change?"