Create a User-Defined Exception

UpComing SoftWare Training Demos

🚀 *Playwright With AI Testing Demo In Telugu*
🗓️ *Date:* 28 Oct2026, 08:00 PM IST
📝 *Register Now!:*
https://www.vlrt.in/3r
👥 *Join WA Community:*
https://www.vlrt.in/3w
💡 *Course Content:*
https://www.vlrt.in/3c
▶️ *Demo Videos:*
https://www.vlrt.in/3v

🚀 *Gen AI Engineer (Production Focused)*
🗓️ *Date:* 29th Oct 2026, 06:00PM IST
📝 *Register Now!:*
https://www.vlrt.in/gr
👥 *Join WA Community:*
https://www.vlrt.in/gw
💡*Course Content:*
https://www.vlrt.in/ai
▶️ *Demo Videos:*
https://www.vlrt.in/gv

🚀 *Vulnerability Management Training Demo*
🗓️ *Date:* 28th Oct 2026, 10:00 AM IST
📝*Register Now!:*
https://www.vlrt.in/vr
👥 *Join Community:*
https://www.vlrt.in/cw
💡 *Course Content:*
https://www.vlrt.in/vc
▶️ *Demo Videos:*
https://www.vlrt.in/Vm

A user-defined exception in Python is a custom error class that you create to handle specific error conditions within your code. Instead of relying on built-in exceptions like ValueError, you define your own to make your code more readable and to provide more specific error messages.

You create a user-defined exception by defining a new class that inherits from the built-in Exception class, or one of its subclasses. This is a standard part of object-oriented programming in Python.

How to Create a User-Defined Exception

To create a custom exception, you define a class that inherits from Exception. The simplest form looks like this:

Python

class CustomError(Exception):
    pass

You can then raise this exception using the raise keyword when a specific error condition is met in your program.

Python

def check_positive(number):
    if number < 0:
        raise CustomError("The number must be positive.")
    return number

You can then handle this custom error using a standard try...except block, just like you would with any other exception.

Python

try:
    check_positive(-5)
except CustomError as e:
    print(f"Caught an error: {e}")

Adding Custom Attributes and Behavior

For more complex scenarios, you can add an __init__ method to your custom exception class to store more detailed information about the error.

Python

class InsufficientFundsError(Exception):
    def __init__(self, required, available):
        self.required = required
        self.available = available
        super().__init__(f"Transaction requires {required}, but only {available} is available.")

When you raise this exception, you can pass the specific details, and they will be stored as attributes of the exception object.

Python

def withdraw(amount, balance):
    if amount > balance:
        raise InsufficientFundsError(amount, balance)
    
withdraw(200, 100)

By defining your own exceptions, you make your code’s error handling more explicit and meaningful, allowing other developers (and your future self) to understand exactly what went wrong without needing to dig through the code.

User-Defined Exceptions in Python

User-defined exceptions are custom exception classes that you create to handle specific error conditions in your application. They inherit from Python’s built-in Exception class or its subclasses.

Why Use User-Defined Exceptions?

  • Make your code more readable and maintainable
  • Handle application-specific error conditions
  • Provide more specific error information
  • Follow the principle of “catch specific exceptions”

Basic Syntax:

python

class CustomError(Exception):
    """Base class for custom exceptions"""
    pass

class SpecificError(CustomError):
    """Specific exception with custom message"""
    def __init__(self, message):
        self.message = message
        super().__init__(self.message)

5 Basic Examples:

Example 1: Basic Custom Exception

python

class InvalidAgeError(Exception):
    """Exception raised for invalid age input"""
    
    def __init__(self, age, message="Age must be between 0 and 120"):
        self.age = age
        self.message = message
        super().__init__(self.message)
    
    def __str__(self):
        return f"{self.message} - Got: {self.age}"

# Usage
def check_age(age):
    if not (0 <= age <= 120):
        raise InvalidAgeError(age)
    print(f"Age {age} is valid!")

try:
    check_age(150)
except InvalidAgeError as e:
    print(f"Error: {e}")

Example 2: Banking Application Exception

python

class InsufficientFundsError(Exception):
    """Exception raised when withdrawal amount exceeds balance"""
    
    def __init__(self, balance, amount):
        self.balance = balance
        self.amount = amount
        super().__init__(f"Insufficient funds: Balance ${balance}, Attempted withdrawal: ${amount}")

class BankAccount:
    def __init__(self, balance=0):
        self.balance = balance
    
    def withdraw(self, amount):
        if amount > self.balance:
            raise InsufficientFundsError(self.balance, amount)
        self.balance -= amount
        return self.balance

# Usage
account = BankAccount(100)
try:
    account.withdraw(200)
except InsufficientFundsError as e:
    print(f"Transaction failed: {e}")

Example 3: Validation Exception Hierarchy

python

class ValidationError(Exception):
    """Base validation error"""
    pass

class EmailFormatError(ValidationError):
    """Invalid email format"""
    pass

class PasswordStrengthError(ValidationError):
    """Weak password"""
    pass

def validate_user(email, password):
    if "@" not in email:
        raise EmailFormatError(f"Invalid email format: {email}")
    if len(password) < 8:
        raise PasswordStrengthError("Password must be at least 8 characters")
    print("Validation successful!")

# Usage
try:
    validate_user("user.example.com", "123")
except ValidationError as e:
    print(f"Validation error: {e}")

Example 4: File Processing Custom Exception

python

class FileProcessingError(Exception):
    """Base exception for file processing errors"""
    pass

class FileTooLargeError(FileProcessingError):
    """File exceeds size limit"""
    def __init__(self, file_size, max_size):
        self.file_size = file_size
        self.max_size = max_size
        super().__init__(f"File size {file_size}MB exceeds maximum {max_size}MB")

class UnsupportedFormatError(FileProcessingError):
    """Unsupported file format"""
    pass

def process_file(filename, size_mb):
    MAX_SIZE = 10  # MB
    
    if not filename.endswith(('.txt', '.csv')):
        raise UnsupportedFormatError(f"Unsupported format: {filename}")
    
    if size_mb > MAX_SIZE:
        raise FileTooLargeError(size_mb, MAX_SIZE)
    
    print(f"Processing {filename}...")

# Usage
try:
    process_file("data.pdf", 15)
except FileProcessingError as e:
    print(f"File error: {e}")

Example 5: E-commerce Application Exceptions

python

class ShoppingCartError(Exception):
    """Base shopping cart exception"""
    pass

class OutOfStockError(ShoppingCartError):
    """Item is out of stock"""
    def __init__(self, item_name):
        self.item_name = item_name
        super().__init__(f"'{item_name}' is out of stock")

class QuantityLimitError(ShoppingCartError):
    """Exceeds quantity limit"""
    def __init__(self, item_name, max_quantity):
        self.item_name = item_name
        self.max_quantity = max_quantity
        super().__init__(f"'{item_name}' limit is {max_quantity} per customer")

class ShoppingCart:
    def __init__(self):
        self.inventory = {"laptop": 5, "mouse": 0, "keyboard": 10}
        self.max_quantities = {"laptop": 2, "mouse": 5, "keyboard": 3}
    
    def add_item(self, item_name, quantity):
        if item_name not in self.inventory:
            raise ShoppingCartError(f"Item '{item_name}' not found")
        
        if self.inventory[item_name] == 0:
            raise OutOfStockError(item_name)
        
        if quantity > self.max_quantities.get(item_name, 1):
            raise QuantityLimitError(item_name, self.max_quantities[item_name])
        
        print(f"Added {quantity} {item_name}(s) to cart")

# Usage
cart = ShoppingCart()
try:
    cart.add_item("mouse", 1)  # Out of stock
    cart.add_item("laptop", 5)  # Exceeds limit
except ShoppingCartError as e:
    print(f"Shopping error: {e}")

Best Practices for User-Defined Exceptions:

  1. Inherit from appropriate base classes (Exception or its subclasses)
  2. Use descriptive names ending with “Error”
  3. Provide meaningful error messages
  4. Create exception hierarchies for related errors
  5. Include relevant data in the exception object
  6. Document your exceptions with docstrings

Example with Multiple Exception Handling:

python

try:
    cart.add_item("laptop", 3)
except OutOfStockError:
    print("Sorry, this item is out of stock")
except QuantityLimitError as e:
    print(f"Quantity limit exceeded: {e}")
except ShoppingCartError as e:
    print(f"General cart error: {e}")
except Exception as e:
    print(f"Unexpected error: {e}")

User-defined exceptions make your code more robust, readable, and maintainable by providing clear, application-specific error handling.

Similar Posts

  • Thonny: A User-Friendly Python IDE for Beginners in 2025

    Thonny is a free and open-source Integrated Development Environment (IDE) specifically designed for beginners learning Python. It provides a simple and user-friendly interface, making it an excellent choice for those new to programming. Key Features: Why Thonny is good for beginners: How to install Thonny: If you’re new to Python and looking for a user-friendly…

  • Object: Methods and properties

    🚗 Car Properties ⚙️ Car Methods 🚗 Car Properties Properties are the nouns that describe a car. They are the characteristics or attributes that define a specific car’s state. Think of them as the data associated with a car object. Examples: ⚙️ Car Methods Methods are the verbs that describe what a car can do….

  • Dictionaries

    Python Dictionaries: Explanation with Examples A dictionary in Python is an unordered collection of items that stores data in key-value pairs. Dictionaries are: Creating a Dictionary python # Empty dictionary my_dict = {} # Dictionary with initial values student = { “name”: “John Doe”, “age”: 21, “courses”: [“Math”, “Physics”, “Chemistry”], “GPA”: 3.7 } Accessing Dictionary Elements…

  • Python Nested Lists

    Python Nested Lists: Explanation & Examples A nested list is a list that contains other lists as its elements. They are commonly used to represent matrices, tables, or hierarchical data structures. 1. Basic Nested List Creation python # A simple 2D list (matrix) matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]…

  • append(), extend(), and insert() methods in Python lists

    append(), extend(), and insert() methods in Python lists, along with slicing where applicable. 1. append() Method Adds a single element to the end of the list. Examples: 2. extend() Method Adds multiple elements (iterable items) to the end of the list. Examples: 3. insert() Method Inserts an element at a specific position. Examples: Key Differences: Method Modifies List? Adds Single/Multiple Elements? Position append() ✅ Yes Single element (even if it’s a list) End…

Leave a Reply

Your email address will not be published. Required fields are marked *