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

  • Python Calendar Module

    Python Calendar Module The calendar module in Python provides functions for working with calendars, including generating calendar data for specific months or years, determining weekdays, and performing various calendar-related operations. Importing the Module python import calendar Key Methods in the Calendar Module 1. calendar.month(year, month, w=2, l=1) Returns a multiline string with a calendar for the specified month….

  • String Validation Methods

    Complete List of Python String Validation Methods Python provides several built-in string methods to check if a string meets certain criteria. These methods return True or False and are useful for input validation, data cleaning, and text processing. 1. Case Checking Methods Method Description Example isupper() Checks if all characters are uppercase “HELLO”.isupper() → True islower() Checks if all…

  • install Python, idle, Install pycharm

    Step 1: Download Python Step 2: Install Python Windows macOS Linux (Debian/Ubuntu) Open Terminal and run: bash Copy Download sudo apt update && sudo apt install python3 python3-pip For Fedora/CentOS: bash Copy Download sudo dnf install python3 python3-pip Step 3: Verify Installation Open Command Prompt (Windows) or Terminal (macOS/Linux) and run: bash Copy Download python3 –version # Should show…

  • Closure Functions in Python

    Closure Functions in Python A closure is a function that remembers values from its enclosing lexical scope even when the program flow is no longer in that scope. Simple Example python def outer_function(x): # This is the enclosing scope def inner_function(y): # inner_function can access ‘x’ from outer_function’s scope return x + y return inner_function…

  • What are Variables

    A program is essentially a set of instructions that tells a computer what to do. Just like a recipe guides a chef, a program guides a computer to perform specific tasks—whether it’s calculating numbers, playing a song, displaying a website, or running a game. Programs are written in programming languages like Python, Java, or C++,…

  • Python Functions

    A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing. Defining a Function In Python, a function is defined using the def keyword, followed by the function name, a set of parentheses (),…

Leave a Reply

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