Create a User-Defined Exception

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

  • Combined Character Classes

    Combined Character Classes Explained with Examples 1. [a-zA-Z0-9_] – Word characters (same as \w) Description: Matches any letter (lowercase or uppercase), any digit, or underscore Example 1: Extract all word characters from text python import re text = “User_name123! Email: test@example.com” result = re.findall(r'[a-zA-Z0-9_]’, text) print(result) # [‘U’, ‘s’, ‘e’, ‘r’, ‘_’, ‘n’, ‘a’, ‘m’, ‘e’, ‘1’, ‘2’,…

  • 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…

  • Variable Length Keyword Arguments in Python

    Variable Length Keyword Arguments in Python Variable length keyword arguments allow a function to accept any number of keyword arguments. This is done using the **kwargs syntax. Syntax python def function_name(**kwargs): # function body # kwargs becomes a dictionary containing all keyword arguments Simple Examples Example 1: Basic **kwargs python def print_info(**kwargs): print(“Information received:”, kwargs) print(“Type of…

  • Demo And course Content

    What is Python? Python is a high-level, interpreted, and general-purpose programming language known for its simplicity and readability. It supports multiple programming paradigms, including: Python’s design philosophy emphasizes code readability (using indentation instead of braces) and developer productivity. History of Python Fun Fact: Python is named after Monty Python’s Flying Circus (a British comedy show), not the snake! 🐍🎭 Top Career Paths After Learning Core Python 🐍…

  • Python Modules: Creation and Usage Guide

    Python Modules: Creation and Usage Guide What are Modules in Python? Modules are simply Python files (with a .py extension) that contain Python code, including: They help you organize your code into logical units and promote code reusability. Creating a Module 1. Basic Module Creation Create a file named mymodule.py: python # mymodule.py def greet(name): return f”Hello, {name}!”…

  • re.fullmatch() Method

    Python re.fullmatch() Method Explained The re.fullmatch() method checks if the entire string matches the regular expression pattern. It returns a match object if the whole string matches, or None if it doesn’t. Syntax python re.fullmatch(pattern, string, flags=0) import re # Target string string = “The Euro STOXX 600 index, which tracks all stock markets across Europe including the FTSE, fell by…

Leave a Reply

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