Custom Exceptions
Create custom exception classes for domain-specific errors. This makes error handling clearer and more maintainable.
15 min•By Priygop Team•Updated 2026
Custom Exceptions
Custom Exceptions
# Custom exception classes
class ValidationError(Exception):
def __init__(self, field, message):
self.field = field
self.message = message
super().__init__(f"{field}: {message}")
class InsufficientFundsError(Exception):
def __init__(self, balance, amount):
self.balance = balance
self.amount = amount
super().__init__(f"Need ${amount}, have ${balance}")
# Using custom exceptions
def validate_age(age):
if not isinstance(age, int):
raise ValidationError("age", "Must be an integer")
if age < 0 or age > 150:
raise ValidationError("age", "Must be 0-150")
return age
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError(balance, amount)
return balance - amount
# Handling custom exceptions
try:
validate_age(-5)
except ValidationError as e:
print(f"Validation failed: {e}")
try:
new_balance = withdraw(100, 500)
except InsufficientFundsError as e:
print(f"Transaction failed: {e}")
print(f" Deficit: ${e.amount - e.balance}")Tip
Tip
Inherit from specific built-in exceptions: class NotFound(ValueError):. This lets callers catch your specific error or the parent type.
Diagram
Loading diagram…
Catch specific exceptions. Use else for success logic. finally for cleanup. Custom exceptions for your domain.
Common Mistake
Warning
Raising generic Exception('error'). Create specific custom exceptions for your domain — it makes error handling much cleaner.
Practice Task
Note
(1) Create InsufficientFundsError with custom attributes. (2) Raise and catch it. (3) Add an error code and message.