π οΈ Python User-defined Exceptions β Create Custom Error Classes Easily
π§² Introduction β Why Use User-defined Exceptions?
Built-in exceptions like ValueError
, TypeError
, and IndexError
work greatβbut what if you’re developing a banking app and want to raise a InsufficientBalanceError
? Or you’re validating configuration files and want a custom InvalidConfigError
?
This is where user-defined exceptions shine. Python lets you create custom exception classes tailored to your applicationβs logic, making error handling more descriptive, more organized, and easier to debug.
π― In this guide, you’ll learn:
- How to define custom exception classes in Python
- How to use them in real projects
- How to add messages and attributes
- Best practices for exception hierarchy
- Tips and common mistakes to avoid
β How to Define a User-defined Exception
class MyCustomError(Exception):
pass
raise MyCustomError("This is a custom error.")
β Explanation:
- You create your exception by inheriting from
Exception
- You can provide a custom error message
- Python treats it like any other exception
π§ͺ Real-world Example β Bank Withdrawal
class InsufficientBalanceError(Exception):
pass
def withdraw(balance, amount):
if amount > balance:
raise InsufficientBalanceError("Balance too low for withdrawal.")
return balance - amount
withdraw(100, 150)
β Output:
InsufficientBalanceError: Balance too low for withdrawal.
π‘ Great for custom validation in finance, user input, or domain-specific rules.
π§ Adding Custom Attributes
class InvalidAgeError(Exception):
def __init__(self, age):
super().__init__(f"Invalid age: {age}")
self.age = age
try:
age = -5
if age < 0:
raise InvalidAgeError(age)
except InvalidAgeError as e:
print(e)
print("Age provided:", e.age)
β Output:
Invalid age: -5
Age provided: -5
π‘ You can store extra data in your exception for custom debugging or logging.
π§± Exception Inheritance Hierarchy
class AppError(Exception): # Base exception
pass
class AuthError(AppError): # More specific
pass
class TokenExpiredError(AuthError): # Even more specific
pass
π‘ Use hierarchies to group related errors and catch them selectively:
try:
raise TokenExpiredError("Token expired")
except AuthError:
print("Caught an authentication error")
π Best Practices for Custom Exceptions
β Do This | β Avoid This |
---|---|
Inherit from Exception or a base class | Inheriting from BaseException |
Create a hierarchy (Base > Specific) | Creating unrelated one-off exceptions |
Include useful messages/attributes | Leaving out __init__() for clarity |
Use meaningful class names | Using generic names like Error1 , etc |
β οΈ Common Mistakes to Avoid
β Mistake | β Fix |
---|---|
Raising a string: raise "Oops" | raise Exception("Oops") |
Not inheriting from Exception | Always use class MyError(Exception): |
Raising without a message | Always provide context in messages |
π Summary β Recap & Next Steps
User-defined exceptions give you precision and control when handling errors. Whether it’s a finance app, web API, or data pipelineβcustom errors let you enforce your own logic cleanly and clearly.
π Key Takeaways:
- β
Inherit from
Exception
to create your own error class - β Add messages and attributes for context
- β Use exception hierarchies to organize errors
- β Catch and raise them like built-in exceptions
βοΈ Real-World Relevance:
Used in web frameworks, data validators, APIs, security, and domain-specific applications.
β FAQ β Python User-defined Exceptions
β How do I define a custom exception?
β
Create a class that inherits from Exception
:
class MyError(Exception):
pass
β Can I add custom fields to my exception?
β
Yes, by overriding __init__()
and storing attributes:
class MyError(Exception):
def __init__(self, code):
self.code = code
β Should I inherit from BaseException
?
β No. Always inherit from Exception
unless you are handling system-level events like KeyboardInterrupt
.
β Can I catch my custom exception with a base class?
β Yes, especially if you create a hierarchy:
class AppError(Exception): pass
class LoginError(AppError): pass
try:
raise LoginError("Failed")
except AppError:
print("Caught AppError")
β How do I raise a user-defined exception?
β
Use the raise
keyword:
raise MyCustomError("Something went wrong.")
Share Now :