Exception hierarchy in Python - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
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?
Practice
Solution
Step 1: Understand Python's exception hierarchy
All exceptions in Python inherit fromBaseException, which is the root of the hierarchy.Step 2: Identify the base class
Exceptioninherits fromBaseException, butBaseExceptionis the top-level base class.Final Answer:
BaseException -> Option BQuick Check:
BaseException is the root of all exceptions [OK]
- Confusing Exception with BaseException
- Thinking Error is a built-in base class
- Choosing RuntimeError as base
Solution
Step 1: Recall exception hierarchy for catching exceptions
CatchingExceptioncatches most errors but excludes system-exiting exceptions likeSystemExitandKeyboardInterrupt.Step 2: Identify correct syntax
except Exception:is the standard way to catch all regular exceptions safely.Final Answer:
except Exception: -> Option CQuick Check:
Use Exception to catch all but system-exiting exceptions [OK]
- Using except BaseException catches system exit too
- Catching only RuntimeError misses many exceptions
- Using except SystemExit catches only exit exceptions
try:
x = 1 / 0
except ArithmeticError:
print('ArithmeticError caught')
except ZeroDivisionError:
print('ZeroDivisionError caught')Solution
Step 1: Understand exception hierarchy for ZeroDivisionError
ZeroDivisionErroris a subclass ofArithmeticError.Step 2: Check which except block matches first
SinceArithmeticErrorcomes beforeZeroDivisionError, the first except block catches the exception.Final Answer:
ArithmeticError caught -> Option AQuick Check:
Parent exception catches before child [OK]
- Expecting ZeroDivisionError block to run first
- Thinking exception order does not matter
- Assuming program crashes without handling
try:
open('file.txt')
except IOError:
print('File error')
except FileNotFoundError:
print('File not found')Solution
Step 1: Understand exception hierarchy between IOError and FileNotFoundError
FileNotFoundErroris a subclass ofIOError.Step 2: Check order of except blocks
The more specific exception (FileNotFoundError) must come before the more general (IOError) to avoid unreachable code.Final Answer:
FileNotFoundError should come before IOError -> Option DQuick Check:
Specific exceptions must precede general ones [OK]
- Putting general exceptions before specific ones
- Assuming IOError and FileNotFoundError are unrelated
- Thinking open() requires mode argument always
KeyboardInterrupt and SystemExit. Which is the best way to write the except block?Solution
Step 1: Recall exception hierarchy for KeyboardInterrupt and SystemExit
BothKeyboardInterruptandSystemExitinherit directly fromBaseException, notException.Step 2: Choose except block that excludes these exceptions
except Exception:catches all exceptions exceptKeyboardInterruptandSystemExit, which is the desired behavior.Final Answer:
except Exception: -> Option AQuick Check:
Exception excludes system-exiting exceptions [OK]
- Using except BaseException catches everything including system exit
- Catching KeyboardInterrupt and SystemExit explicitly when not needed
- Combining Exception with KeyboardInterrupt in except tuple
