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

  • What is general-purpose programming language

    A general-purpose programming language is a language designed to be used for a wide variety of tasks and applications, rather than being specialized for a particular domain. They are versatile tools that can be used to build anything from web applications and mobile apps to desktop software, games, and even operating systems. Here’s a breakdown…

  • circle,Rational Number

    1. What is a Rational Number? A rational number is any number that can be expressed as a fraction where both the numerator and the denominator are integers (whole numbers), and the denominator is not zero. The key idea is ratio. The word “rational” comes from the word “ratio.” General Form:a / b Examples: Non-Examples: 2. Formulas for Addition and Subtraction…

  • Polymorphism

    Polymorphism is a core concept in OOP that means “many forms” 🐍. In Python, it allows objects of different classes to be treated as objects of a common superclass. This means you can use a single function or method to work with different data types, as long as they implement a specific action. 🌀 Polymorphism…

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

  • Real-World Applications of Python Lists

    Python lists and their methods are used extensively in real-time applications across various domains. They are fundamental for organizing and manipulating ordered collections of data. Real-World Applications of Python Lists 1. Web Development In web development, lists are crucial for handling dynamic data. For example, a list can store user comments on a post, products…

Leave a Reply

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