Best practices for custom exceptions in Python - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
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?"
Practice
Solution
Step 1: Understand the purpose of custom exceptions
Custom exceptions help programmers identify and handle specific errors clearly.Step 2: Compare with other options
Options B, C, and D are incorrect because custom exceptions do not avoid try-except, speed execution, or replace built-ins.Final Answer:
To make error handling clearer and more specific -> Option AQuick Check:
Custom exceptions clarify errors = A [OK]
- Thinking custom exceptions speed up code
- Believing they replace built-in exceptions
- Assuming they remove need for try-except
Solution
Step 1: Check Python syntax for custom exceptions
Custom exceptions must be classes inheriting from Exception or its subclasses.Step 2: Evaluate each option
A defines a class without inheritance, B defines a function, D uses invalid keyword. Only C ('class MyError(Exception): pass') correctly defines a custom exception.Final Answer:
class MyError(Exception): pass -> Option AQuick Check:
Custom exceptions are classes inheriting Exception = C [OK]
- Defining exceptions as functions
- Not inheriting from Exception
- Using invalid keywords like 'exception'
class MyError(Exception):
pass
try:
raise MyError('Oops!')
except MyError as e:
print(e)Solution
Step 1: Understand the raise statement
The code raises MyError with message 'Oops!'.Step 2: Check the except block output
The except block catches MyError as e and prints e, which is the message 'Oops!'.Final Answer:
Oops! -> Option DQuick Check:
Exception message prints = A [OK]
- Printing exception class name instead of message
- Expecting no output
- Confusing exception type with message
class CustomError:
def __init__(self, message):
self.message = message
raise CustomError('Error occurred')Solution
Step 1: Check inheritance of CustomError
CustomError does not inherit from Exception, so it is not a proper exception class.Step 2: Analyze other options
Raise syntax is correct, attribute name is flexible, __str__ is optional but recommended.Final Answer:
CustomError does not inherit from Exception -> Option BQuick Check:
Custom exceptions must inherit Exception = D [OK]
- Forgetting to inherit from Exception
- Assuming attribute names must be fixed
- Thinking __str__ is mandatory
Solution
Step 1: Check inheritance and initialization
class ErrorCodeException(Exception): def __init__(self, code, message): super().__init__(message) self.code = code inherits Exception and calls super().__init__(message) to set the message properly.Step 2: Compare with other options
class ErrorCodeException(Exception): def __init__(self, code, message): self.code = code self.message = message does not call super().__init__, so message may not behave like a normal exception message. class ErrorCodeException: def __init__(self, code, message): self.code = code self.message = message lacks inheritance. class ErrorCodeException(Exception): pass has no code or message storage.Final Answer:
class ErrorCodeException(Exception): def __init__(self, code, message): super().__init__(message) self.code = code -> Option CQuick Check:
Inherit Exception and call super() with message = B [OK]
- Not calling super().__init__ for message
- Not inheriting from Exception
- Storing message without Exception support
