Python > Core Python Basics > Error Handling > Custom Exceptions

Defining and Raising Custom Exceptions

This snippet demonstrates how to define and raise custom exceptions in Python. Custom exceptions allow you to create specific error types tailored to your application's needs, making error handling more precise and informative.

Defining a Custom Exception

To create a custom exception, define a new class that inherits from the built-in Exception class (or a subclass thereof). It's a good practice to create a base custom exception (like CustomError) and then derive more specific exceptions from it.

The __init__ method is used to initialize the exception with a message. This message can provide context about the error.

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

class ValueTooSmallError(CustomError):
    """Raised when the input value is too small"""
    def __init__(self, message):
        self.message = message

class ValueTooLargeError(CustomError):
    """Raised when the input value is too large"""
    def __init__(self, message):
        self.message = message

Raising a Custom Exception

To raise a custom exception, use the raise keyword followed by an instance of your custom exception class. You can pass arguments to the exception's constructor, typically a descriptive message. The try...except block then handles these custom exceptions appropriately, providing specific responses based on the error encountered. A ValueError exception is also handled in case the user enters non-integer input.

number = 50

try:
    i = int(input("Enter a number: "))
    if i < number:
        raise ValueTooSmallError("This value is too small")
    elif i > number:
        raise ValueTooLargeError("This value is too large")
    else:
        print("You guessed it!")

except ValueTooSmallError as e:
    print(e.message)
except ValueTooLargeError as e:
    print(e.message)
except ValueError:
    print("Invalid input. Please enter an integer.")

Concepts Behind the Snippet

Inheritance: Custom exceptions inherit from the base Exception class, allowing them to be caught like any other exception.
Polymorphism: The except blocks can catch different types of exceptions, including custom ones, based on their class hierarchy.
Encapsulation: The exception class encapsulates the error information, making it easier to handle and propagate errors.

Real-Life Use Case

Imagine an e-commerce application. You might define custom exceptions like InsufficientStockError (when a user tries to order more items than available), InvalidCouponCodeError, or PaymentFailedError. These exceptions provide meaningful information about failures specific to the application domain, enabling targeted error handling and better user experience.

Best Practices

  • Create a base exception class for your application module.
  • Provide meaningful error messages in the exception constructor.
  • Document your custom exceptions.
  • Avoid using generic except Exception: to catch all errors. Be specific about the exceptions you expect to handle.

Interview Tip

Be prepared to discuss why custom exceptions are beneficial. Explain how they improve code readability, maintainability, and error handling accuracy. Illustrate with a practical example from a project you've worked on.

When to Use Them

Use custom exceptions when you need to handle errors that are specific to your application's logic or domain. They are particularly useful when you need to provide different error messages or perform different actions based on the type of error.

Memory Footprint

Custom exceptions, like any other Python class, consume memory. However, the memory footprint is typically small unless you're storing large amounts of data within the exception object itself. Avoid unnecessary data storage within exceptions to minimize memory usage.

Alternatives

While custom exceptions are highly recommended for specific error handling, simpler cases might be handled with built-in exceptions like ValueError, TypeError, or IOError. However, for domain-specific errors, custom exceptions offer superior clarity and maintainability.

Pros

  • Improved code readability and maintainability.
  • More precise error handling.
  • Better error messages.
  • Encapsulation of error information.

Cons

  • Requires more code than simply raising generic exceptions.
  • Can add complexity if not designed carefully.

FAQ

  • Why should I create a base custom exception?

    Creating a base custom exception allows you to catch a group of related exceptions with a single except block. This simplifies error handling and makes your code more maintainable.
  • How do I pass additional data to a custom exception?

    You can add arguments to the exception's __init__ method and store them as attributes of the exception object. These attributes can then be accessed in the except block to retrieve more information about the error.