Python Custom Exceptions
Exceptions are errors that occur during program execution. Python provides many built-in exceptions such as:
- ValueError
- TypeError
- IndexError
- FileNotFoundError
However, in real-world applications, built-in exceptions may not always describe business-specific errors clearly.
This is where Custom Exceptions become useful.
Custom exceptions allow developers to create meaningful error messages tailored to their applications.
What Are Custom Exceptions?
A custom exception is a user-defined exception class that inherits from Python's built-in Exception class.
Custom exceptions help:
- Improve code readability
- Provide meaningful error messages
- Handle application-specific errors
- Simplify debugging
Why Use Custom Exceptions?
Suppose you're building a banking application.
Instead of:
raise ValueError("Invalid operation")You can use:
raise InsufficientFundsError("Balance too low")This makes the error much easier to understand.
Creating a Custom Exception
Basic Example
class CustomError(Exception):
passRaising a Custom Exception
class CustomError(Exception):
pass
raise CustomError("Something went wrong")Output
CustomError: Something went wrongHandling a Custom Exception
class CustomError(Exception):
pass
try:
raise CustomError("Custom exception occurred")
except CustomError as e:
print(e)Output
Custom exception occurredExample: Age Validation
class InvalidAgeError(Exception):
pass
age = -5
if age < 0:
raise InvalidAgeError("Age cannot be negative")Output
InvalidAgeError: Age cannot be negativeCustom Exception with Constructor
You can customize exception messages using __init__().
class InvalidSalaryError(Exception):
def __init__(self, salary):
self.salary = salary
self.message = f"Invalid salary: {salary}"
super().__init__(self.message)Using the Exception
salary = -1000
if salary < 0:
raise InvalidSalaryError(salary)Output
InvalidSalaryError: Invalid salary: -1000Custom Exception Hierarchy
Multiple exceptions can inherit from a common base exception.
class BankError(Exception):
pass
class InsufficientFundsError(BankError):
pass
class AccountClosedError(BankError):
passExample
try:
raise InsufficientFundsError(
"Insufficient balance"
)
except BankError as e:
print(e)Output
Insufficient balanceReal-World Banking Example
class InsufficientFundsError(Exception):
pass
balance = 500
withdraw = 1000
if withdraw > balance:
raise InsufficientFundsError(
"Not enough funds available"
)Custom Exceptions with Additional Data
class ProductNotFoundError(Exception):
def __init__(self, product_id):
self.product_id = product_id
super().__init__(
f"Product {product_id} not found"
)Example
raise ProductNotFoundError(101)Output
Product 101 not foundUsing Custom Exceptions in Functions
class EmptyStringError(Exception):
pass
def validate_name(name):
if not name:
raise EmptyStringError(
"Name cannot be empty"
)
validate_name("")Custom Exceptions in Classes
class InvalidPasswordError(Exception):
pass
class User:
def set_password(self, password):
if len(password) < 8:
raise InvalidPasswordError(
"Password too short"
)
user = User()
user.set_password("123")Exception Chaining
Custom exceptions can wrap other exceptions.
try:
number = int("abc")
except ValueError as e:
raise CustomError(
"Invalid number entered"
) from eBenefits of Exception Chaining
- Preserves original error
- Easier debugging
- Better error tracking
Custom Exceptions vs Built-in Exceptions
| Feature | Built-in Exception | Custom Exception |
|---|---|---|
| Generic Errors | Yes | No |
| Application-Specific | No | Yes |
| Readability | Medium | High |
| Business Logic Support | Limited | Excellent |
Real-World Applications
Custom exceptions are commonly used in:
- Banking systems
- E-commerce platforms
- Authentication systems
- Payment gateways
- Inventory management
- Web APIs
Best Practices
Use Meaningful Names
Good:
class InvalidOrderError(Exception):
passBad:
class Error(Exception):
passInherit from Exception
class MyError(Exception):
passProvide Helpful Messages
raise InvalidEmailError(
"Email format is invalid"
)Group Related Exceptions
class ApplicationError(Exception):
passUse it as a base class for all application errors.
Common Mistakes
Not Inheriting from Exception
Wrong:
class MyError:
passCorrect:
class MyError(Exception):
passUsing Generic Exceptions Everywhere
Avoid:
raise Exception("Error")Use:
raise InvalidUserError(
"User not found"
)Summary
Custom exceptions allow Python developers to create meaningful, application-specific error types. They improve readability, debugging, maintainability, and make error handling more structured.
Conclusion
Custom exceptions are an essential part of professional Python development. By creating your own exception classes, you can build cleaner, more reliable, and easier-to-maintain applications while providing clear and meaningful error messages.


0 Comments