Extending built-in exceptions in Python - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
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?
Practice
Solution
Step 1: Understand the purpose of exceptions
Exceptions help signal errors or unusual situations in a program.Step 2: Why extend built-in exceptions?
Extending allows creating specific error types that explain problems clearly and help debugging.Final Answer:
To create custom error types that describe specific problems clearly -> Option AQuick Check:
Custom exceptions = clearer error messages [OK]
- Thinking extending exceptions speeds up code
- Believing exceptions fix errors automatically
- Confusing exceptions with avoiding try-except
MyError that extends ValueError?Solution
Step 1: Recognize class syntax for exceptions
Custom exceptions are classes that inherit from built-in exceptions.Step 2: Check correct Python class definition
Useclass MyError(ValueError): passto extend ValueError properly.Final Answer:
class MyError(ValueError): pass -> Option BQuick Check:
Use class + inheritance syntax for exceptions [OK]
- Using def instead of class
- Wrong inheritance syntax
- Using 'exception' keyword which doesn't exist
class MyError(Exception):
pass
try:
raise MyError('Oops!')
except MyError as e:
print(e)Solution
Step 1: Understand raising and catching custom exception
The code raisesMyErrorwith message 'Oops!'.Step 2: What does
Printing the exception variableprint(e)show?eshows the message passed during raise.Final Answer:
Oops! -> Option CQuick Check:
Exception message prints when caught and printed [OK]
- Printing exception class name instead of message
- Expecting no output because of exception
- Confusing exception type with message
class CustomError(Exception):
def __init__(self, message):
print(message)Solution
Step 1: Check __init__ method in custom exception
Custom exceptions should call the parent Exception __init__ to set the message properly.Step 2: Why call super().__init__(message)?
This ensures the message is stored and accessible like normal exceptions.Final Answer:
Missing call to super().__init__(message) in __init__ -> Option DQuick Check:
Always call super().__init__ in custom exception init [OK]
- Forgetting super().__init__ call
- Thinking print replaces message storage
- Believing class names must be lowercase
ValidationError that stores an error code along with the message. Which code correctly implements this?Solution
Step 1: Understand storing extra info in custom exceptions
We want to keep both message and code, so __init__ must accept both.Step 2: Properly call super().__init__ with message and store code
class ValidationError(Exception): def __init__(self, message, code): super().__init__(message) self.code = code calls super().__init__(message) to set message and saves code as attribute.Final Answer:
class ValidationError(Exception): def __init__(self, message, code): super().__init__(message) self.code = code -> Option AQuick Check:
Call super with message, store extra attributes separately [OK]
- Not calling super().__init__ with message
- Not storing extra info as attributes
- Mixing message and code parameters
