User Defined Exceptions
While Python's built-in exceptions cover many common situations, you will often need to define your own exception classes to represent errors that are spec...
Creating Custom Exception Classes in Python
While Python's built-in exceptions cover many common situations, you will often need to define your own exception classes to represent errors that are specific to your application or domain. Custom exceptions make error handling more precise and your code easier to understand and maintain.
Creating a custom exception is straightforward. You define a class that inherits from Exception or one of its subclasses. By convention, exception class names end with Error:
class InsufficientFundsError(Exception): def __init__(self, balance, amount): self.balance = balance self.amount = amount super().__init__( f"Cannot withdraw {amount}. Available balance: {balance}" )
class BankAccount: def __init__(self, balance): self.balance = balance
def withdraw(self, amount): if amount > self.balance: raise InsufficientFundsError(self.balance, amount) self.balance -= amount
account = BankAccount(100) try: account.withdraw(200) except InsufficientFundsError as e: print(e) print(f"You tried to withdraw: {e.amount}")
This example shows how custom exceptions can carry extra data beyond a plain message. The amount and balance attributes on the exception object let the except block give the user specific information about what went wrong.
You can create hierarchies of custom exceptions, which is useful for large applications. For example, a web application might define a base AppError and then have subclasses like AuthenticationError, DatabaseError, and ValidationError. Code that handles all application errors can catch AppError, while code that needs to react specifically to login problems catches AuthenticationError.
When you raise a custom exception, Python stores the current traceback so that debugging tools can show you exactly where the error occurred. You can also chain exceptions using the raise ... from ... syntax to preserve context from an original error while replacing it with a more meaningful one.
Interview tip: Custom exceptions show that you design code with error-handling in mind from the start. Interviewers like to see exception hierarchies that make sense for the domain. Mention that inheriting from a specific built-in exception (like ValueError) gives callers more flexibility when deciding what to catch.