Exception hierarchy in Python - Time & Space Complexity
When working with exceptions, it's important to understand how catching errors affects program flow.
We want to see how the time to handle exceptions grows as the number of exception types increases.
Analyze the time complexity of the following code snippet.
def handle_error(e):
if isinstance(e, ValueError):
print("Value error handled")
elif isinstance(e, TypeError):
print("Type error handled")
elif isinstance(e, KeyError):
print("Key error handled")
else:
print("Unknown error")
This code checks the type of an error and handles it accordingly by testing each exception type in order.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking the error type with multiple
isinstancecalls. - How many times: Once for each exception type in the chain until a match is found or all are checked.
As the number of exception types to check grows, the number of type checks grows too.
| Input Size (number of exception types) | Approx. Operations (type checks) |
|---|---|
| 3 | Up to 3 checks |
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
Pattern observation: The number of checks grows directly with the number of exception types to test.
Time Complexity: O(n)
This means the time to handle an exception grows linearly with the number of exception types checked.
[X] Wrong: "Checking exceptions is always constant time because exceptions are rare."
[OK] Correct: Even if exceptions are rare, when they happen, the program may check many exception types one by one, so the time depends on how many types are checked.
Understanding how exception handling scales helps you write clearer and more efficient error management in real projects.
What if we used a dictionary to map exception types to handlers instead of multiple if-elif checks? How would the time complexity change?