Custom exceptions help you handle specific errors clearly in your programs. They make your code easier to understand and fix.
Best practices for custom exceptions in Python
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Python
class MyCustomError(Exception): """Optional docstring explaining this error.""" pass
Custom exceptions usually inherit from Exception or one of its subclasses.
Use a clear and descriptive name ending with Error to show it is an exception.
Examples
Python
class ValidationError(Exception): pass
Python
class DatabaseConnectionError(Exception): def __init__(self, message, db_name): super().__init__(message) self.db_name = db_name
ValueError to be more specific about the error type.Python
class FileFormatError(ValueError): """Raised when a file has wrong format.""" pass
Sample Program
This program defines a custom exception NegativeNumberError. It raises this error if the number is negative. The try-except block catches and prints the error message.
Python
class NegativeNumberError(Exception): """Raised when a negative number is not allowed.""" pass def check_positive(number): if number < 0: raise NegativeNumberError(f"Negative number not allowed: {number}") return True try: check_positive(-5) except NegativeNumberError as e: print(f"Caught an error: {e}")
Important Notes
Always give your custom exceptions clear and meaningful names.
Include helpful messages or extra data to make debugging easier.
Use inheritance to group related exceptions together.
Summary
Custom exceptions make error handling clearer and more specific.
Name exceptions clearly and inherit from Exception or related classes.
Add messages or extra info to help understand the error.
Practice
1. Why is it a good practice to create custom exceptions in Python?
easy
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]
Hint: Custom exceptions clarify specific errors [OK]
Common Mistakes:
- Thinking custom exceptions speed up code
- Believing they replace built-in exceptions
- Assuming they remove need for try-except
2. Which of the following is the correct way to define a custom exception in Python?
easy
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]
Hint: Custom exceptions are classes inheriting Exception [OK]
Common Mistakes:
- Defining exceptions as functions
- Not inheriting from Exception
- Using invalid keywords like 'exception'
3. What will be the output of this code?
class MyError(Exception):
pass
try:
raise MyError('Oops!')
except MyError as e:
print(e)medium
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]
Hint: Exception message prints when caught and printed [OK]
Common Mistakes:
- Printing exception class name instead of message
- Expecting no output
- Confusing exception type with message
4. Identify the error in this custom exception definition:
class CustomError:
def __init__(self, message):
self.message = message
raise CustomError('Error occurred')medium
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]
Hint: Always inherit Exception for custom exceptions [OK]
Common Mistakes:
- Forgetting to inherit from Exception
- Assuming attribute names must be fixed
- Thinking __str__ is mandatory
5. You want to create a custom exception that stores an error code and a message. Which is the best practice to implement it?
hard
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]
Hint: Call super().__init__(message) to set exception message [OK]
Common Mistakes:
- Not calling super().__init__ for message
- Not inheriting from Exception
- Storing message without Exception support
