Python Custom Exceptions
What Are Custom Exceptions in Python?
Custom exceptions (also called user-defined exceptions) let you define your own error types for specific situations in your application logic—beyond Python's built-in exceptions like ValueError, IndexError, or TypeError.
Why Use Custom Exceptions?
- To represent domain-specific errors (e.g., InvalidEmailError)
- To make your code more readable and maintainable
- To handle errors more precisely
How to Create a Custom Exception
Syntax:
class CustomError(Exception):
"""Custom exception class"""
pass
This inherits from the built-in Exception class.
Example 1: Simple Custom Exception
class NegativeAgeError(Exception):
"""Raised when the age is negative"""
pass
def set_age(age):
if age < 0:
raise NegativeAgeError("Age cannot be negative!")
print("Age is set to:", age)
try:
set_age(-5)
except NegativeAgeError as e:
print("Caught custom exception:", e)
Output:
Caught custom exception: Age cannot be negative!
Example 2: Custom Exception with Constructor
class BankBalanceError(Exception):
def __init__(self, balance, message="Insufficient funds"):
self.balance = balance
self.message = message
super().__init__(self.message)
def withdraw(balance):
if balance < 100:
raise BankBalanceError(balance)
print("Withdrawal successful!")
try:
withdraw(50)
except BankBalanceError as e:
print(f"Error: {e.message} (Balance: ${e.balance})")
Output:
Error: Insufficient funds (Balance: $50)
Tips for Creating User-Defined Exceptions
- Inherit from Exception (not BaseException)
- Use meaningful class names like InvalidInputError, AuthenticationError
- Add docstrings for clarity
- Optionally override __init__() and __str__() methods
Best Practices
Use custom exceptions to separate logic errors from system errors.
Keep exception hierarchies clean: group similar custom exceptions under a base custom class if needed.
class ApplicationError(Exception):
pass
class AuthError(ApplicationError):
pass
class PermissionDeniedError(ApplicationError):
pass