Create a User-Defined Exception

UpComing SoftWare Training Demos

πŸš€ *Gen AI EngineerΒ Telugu (Production Focused)*
πŸ—“οΈ *Date:* 30th Sept 2026, 07:00AM 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

πŸš€ *Service now Admin/ Development (ITSM)FREE Demo in Telugu*
πŸ—“οΈ *Date:* 30th Sept 2026, 08:00AM IST
πŸ“ *Register Now!:*
https://www.vlrt.in/7r
πŸ‘₯ *Join WA Community:*
https://www.vlrt.in/7w
πŸ’‘*Course Content:*
https://www.vlrt.in/7c
▢️ *Demo Videos:*
https://www.vlrt.in/7v

πŸš€ *Vulnerability Management Training Demo*
πŸ—“οΈ *Date:* 30th Sept 2026, 09: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

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

  • Functions as Objects

    Functions as Objects and First-Class Functions in Python In Python, functions are first-class objects, which means they can be: 1. Functions as Objects In Python, everything is an object, including functions. When you define a function, you’re creating a function object. python def greet(name): return f”Hello, {name}!” # The function is an object with type ‘function’…

  • Method overriding

    Method overriding is a key feature of object-oriented programming (OOP) and inheritance. It allows a subclass (child class) to provide its own specific implementation of a method that is already defined in its superclass (parent class). When a method is called on an object of the child class, the child’s version of the method is…

  • Strings in PythonΒ Indexing,Traversal

    Strings in Python and Indexing Strings in Python are sequences of characters enclosed in single quotes (‘ ‘), double quotes (” “), or triple quotes (”’ ”’ or “”” “””). They are immutable sequences of Unicode code points used to represent text. String Characteristics Creating Strings python single_quoted = ‘Hello’ double_quoted = “World” triple_quoted = ”’This is…

  • Iterators in Python

    Iterators in Python An iterator in Python is an object that is used to iterate over iterable objects like lists, tuples, dictionaries, and sets. An iterator can be thought of as a pointer to a container’s elements. To create an iterator, you use the iter() function. To get the next element from the iterator, you…

Leave a Reply

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