⚠️ What are Custom Exceptions in Python?
While Python provides many built-in exceptions (like ValueError, TypeError, or KeyError), complex applications often require domain-specific error handling.
You can create custom exceptions by defining a new class that inherits directly or indirectly from Python's built-in Exception class.
1. Basic Custom Exception Syntax
Define a simple custom exception class using inheritance and raise it using the
raise keyword.
Python
# Defining a custom exception class
class InvalidAgeError(Exception):
"""Raised when entered age is outside valid range."""
pass
def validate_age(age):
if age < 18 or age > 100:
raise InvalidAgeError("Age must be between 18 and 100.")
return "Age is valid."
try:
validate_age(15)
except InvalidAgeError as e:
print("Caught Custom Exception:", e)
Output:
Caught Custom Exception: Age must be between 18 and 100.
Real-Time Example 1: Insufficient Account Balance Exception
Raise a custom
InsufficientBalanceError when a bank withdrawal exceeds available funds.
Python
class InsufficientBalanceError(Exception):
pass
class BankAccount:
def __init__(self, holder, balance):
self.holder = holder
self.balance = balance
def withdraw(self, amount):
if amount > self.balance:
raise InsufficientBalanceError(f"Attempted to withdraw ₹{amount}, but balance is only ₹{self.balance}")
self.balance -= amount
return f"Withdrawal successful. Remaining balance: ₹{self.balance}"
acc = BankAccount("Rahul Sharma", 5000)
try:
print(acc.withdraw(8000))
except InsufficientBalanceError as e:
print("Transaction Denied:", e)
Output:
Transaction Denied: Attempted to withdraw ₹8000, but balance is only ₹5000
Real-Time Example 2: E-Commerce Out of Stock Exception
Trigger a custom inventory exception when order quantities exceed warehouse stock levels.
Python
class OutOfStockError(Exception):
def __init__(self, item, requested, available):
self.message = f"Item '{item}' out of stock. Requested: {requested}, Available: {available}"
super().__init__(self.message)
def process_order(item, stock, requested):
if requested > stock:
raise OutOfStockError(item, requested, stock)
return f"Order confirmed for {requested} units of {item}."
try:
print(process_order("Wireless Mouse", 5, 12))
except OutOfStockError as e:
print("Inventory Error:", e)
Output:
Inventory Error: Item 'Wireless Mouse' out of stock. Requested: 12, Available: 5
Real-Time Example 3: Authentication Lockout Exception
Raise a custom security exception after multiple failed login attempts.
Python
class AccountLockedError(Exception):
pass
class LoginManager:
def __init__(self):
self.failed_attempts = 0
def attempt_login(self, password):
correct_password = "secret_password"
if password != correct_password:
self.failed_attempts += 1
if self.failed_attempts >= 3:
raise AccountLockedError("Security Lockout: Account locked due to 3 failed login attempts.")
print(f"Incorrect password. Attempts remaining: {3 - self.failed_attempts}")
else:
print("Login successful!")
manager = LoginManager()
try:
manager.attempt_login("wrong1")
manager.attempt_login("wrong2")
manager.attempt_login("wrong3")
except AccountLockedError as e:
print("Security Alert:", e)
Output:
Incorrect password. Attempts remaining: 2
Incorrect password. Attempts remaining: 1
Security Alert: Security Lockout: Account locked due to 3 failed login attempts.
Real-Time Example 4: API Rate Limit Exceeded Exception
Throw a custom rate limit exception when clients exceed maximum API request thresholds.
Python
class RateLimitExceededError(Exception):
def __init__(self, retry_after_sec):
super().__init__(f"API Rate limit reached. Please retry after {retry_after_sec} seconds.")
self.retry_after_sec = retry_after_sec
def make_api_call(request_count):
if request_count > 100:
raise RateLimitExceededError(60)
return "API Request processed."
try:
make_api_call(150)
except RateLimitExceededError as e:
print("API Error:", e)
print(f"Header 'Retry-After': {e.retry_after_sec}s")
Output:
API Error: API Rate limit reached. Please retry after 60 seconds.
Header 'Retry-After': 60s
Real-Time Example 5: Weak Password Complexity Exception
Validate password strength during user registration and raise custom complexity errors.
Python
class WeakPasswordError(Exception):
pass
def register_password(password):
if len(password) < 8 or not any(char.isdigit() for char in password):
raise WeakPasswordError("Password must be at least 8 characters long and contain a number.")
return "Password accepted."
try:
register_password("abc")
except WeakPasswordError as e:
print("Registration Failed:", e)
Output:
Registration Failed: Password must be at least 8 characters long and contain a number.
Real-Time Example 6: Custom Exception with Logging
Capture custom exceptions and record error telemetry timestamps for auditing.
Python
import datetime
class DatabaseConnectionError(Exception):
def __init__(self, message):
super().__init__(message)
self.timestamp = datetime.datetime.now()
def connect_db(status):
if status == "offline":
raise DatabaseConnectionError("Failed to establish server socket connection.")
return "Connected."
try:
connect_db("offline")
except DatabaseConnectionError as e:
print(f"[LOG {e.timestamp}] Critical Error: {e}")
Output:
[LOG 2026-10-27 10:05:00.000000] Critical Error: Failed to establish server socket connection.
Real-Time Example 7: Handling Multiple Custom Exceptions
Group multiple related custom exceptions under a shared base exception class for clean handling.
Python
class BillingError(Exception):
"""Base billing exception."""
pass
class CardDeclinedError(BillingError):
pass
class ExpiredCardError(BillingError):
pass
def process_payment(card_status):
if card_status == "declined":
raise CardDeclinedError("Payment card was declined by issuing bank.")
elif card_status == "expired":
raise ExpiredCardError("Payment card has expired.")
try:
process_payment("expired")
except BillingError as e:
print("Billing Exception Caught:", e)
Output:
Billing Exception Caught: Payment card has expired.
Real-Time Example 8: Invalid File Format Exception
Raise a custom exception when users upload unsupported file formats.
Python
class InvalidFileFormatError(Exception):
pass
def upload_document(filename):
if not filename.endswith((".pdf", ".docx")):
raise InvalidFileFormatError(f"File '{filename}' is not supported. Please upload PDF or DOCX.")
return "Document uploaded successfully."
try:
upload_document("script.exe")
except InvalidFileFormatError as e:
print("Upload Error:", e)
Output:
Upload Error: File 'script.exe' is not supported. Please upload PDF or DOCX.
Real-Time Example 9: Booking Date Conflict Exception
Raise a custom exception when appointment scheduling conflicts with existing bookings.
Python
class DateConflictError(Exception):
pass
booked_dates = ["2026-11-15", "2026-11-16"]
def book_appointment(date_str):
if date_str in booked_dates:
raise DateConflictError(f"Date {date_str} is already booked. Please choose another slot.")
return f"Appointment confirmed for {date_str}."
try:
print(book_appointment("2026-11-15"))
except DateConflictError as e:
print("Booking Conflict:", e)
Output:
Booking Conflict: Date 2026-11-15 is already booked. Please choose another slot.