Defining Custom Exceptions in Python
While Python's built-in exceptions cover a wide range of error scenarios, there may be times when you need to define your own custom exceptions to handle specific situations in your application. Defining custom exceptions can improve the readability and maintainability of your code, as well as provide more meaningful error messages to your users.
Creating Custom Exceptions
To define a custom exception in Python, you can create a new class that inherits from the Exception
class or one of its subclasses. This allows you to create exceptions that are tailored to your specific use case.
class CustomException(Exception):
pass
In the above example, we've created a new exception class called CustomException
that inherits from the Exception
class.
You can also add additional attributes or methods to your custom exception class to provide more information or functionality.
class InsufficientFundsError(Exception):
def __init__(self, balance, amount):
self.balance = balance
self.amount = amount
def __str__(self):
return f"Insufficient funds. Current balance: {self.balance}, Requested amount: {self.amount}"
In this example, we've created a custom exception called InsufficientFundsError
that includes the current balance and the requested amount as attributes. The __str__
method is overridden to provide a more informative error message.
Raising Custom Exceptions
To raise a custom exception, you can use the raise
statement, just like you would with built-in exceptions.
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError(balance, amount)
else:
return balance - amount
try:
new_balance = withdraw(100, 150)
except InsufficientFundsError as e:
print(e)
In the above example, the withdraw
function raises an InsufficientFundsError
if the requested amount exceeds the current balance. The try-except
block catches the custom exception and prints the error message.
By defining and using custom exceptions, you can create a more expressive and self-documenting codebase, making it easier for other developers (or your future self) to understand and maintain your application.