Extending built-in exceptions in Python - Time & Space Complexity
When we extend built-in exceptions in Python, we add custom behavior to error handling.
We want to see how the time to create and raise these exceptions changes as input grows.
Analyze the time complexity of this custom exception class and its usage.
class MyError(Exception):
def __init__(self, message, code):
super().__init__(message)
self.code = code
def check_value(x):
if x < 0:
raise MyError('Negative value', x)
return x
This code defines a new error type and raises it when a value is negative.
Look for loops or repeated actions that affect time.
- Primary operation: Creating and raising the custom exception.
- How many times: Once per call to
check_valuewhen input is negative.
Each call to check_value does a simple check and may raise an exception.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks, few exceptions if any |
| 100 | 100 checks, exceptions only when input is negative |
| 1000 | 1000 checks, exceptions rare or frequent based on input |
Pattern observation: Time grows linearly with number of calls, exception creation cost is constant per raise.
Time Complexity: O(n)
This means the time grows directly with how many times you call the function, since each call does a simple check.
[X] Wrong: "Creating a custom exception makes the program slower exponentially."
[OK] Correct: Creating and raising exceptions takes constant time each time, so it does not grow exponentially with input size.
Understanding how custom exceptions affect performance helps you write clear and efficient error handling in real projects.
What if the exception included a large data structure as a property? How would the time complexity change?