Python > Core Python Basics > Error Handling > Exceptions
Raising Custom Exceptions
This snippet shows how to define and raise custom exceptions in Python. Custom exceptions allow you to create specific error types tailored to your application's needs, improving code clarity and maintainability.
Code Example
We define a custom exception class InsufficientFundsError
that inherits from the built-in Exception
class. The __init__
method initializes the exception with a custom error message. The withdraw
function checks if the withdrawal amount exceeds the balance. If it does, it raises the InsufficientFundsError
with a descriptive message. The try-except
block catches the custom exception and prints the error message.
class InsufficientFundsError(Exception):
def __init__(self, message):
super().__init__(message)
self.message = message
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError("Insufficient funds in your account.")
new_balance = balance - amount
print("Withdrawal successful. New balance:", new_balance)
return new_balance
balance = 100
try:
balance = withdraw(balance, 150)
except InsufficientFundsError as e:
print("Error:", e.message)
# Error: Insufficient funds in your account.
Concepts Behind the Snippet
Custom exceptions provide a way to signal specific error conditions within your application domain. By creating meaningful exception types, you can make your code more readable and easier to debug. Inheriting from the base Exception
class ensures that your custom exceptions behave like standard Python exceptions.
Real-Life Use Case
In an e-commerce application, you might define custom exceptions like ProductNotFoundError
, InvalidOrderError
, or PaymentFailedError
to handle specific problems during product retrieval, order processing, and payment transactions.
Best Practices
Interview Tip
Be prepared to explain the benefits of using custom exceptions over generic exceptions. Demonstrate your understanding of how to define and raise custom exceptions in Python.
When to Use Them
Use custom exceptions when you need to signal specific error conditions that are unique to your application or domain. This helps to make your code more expressive and easier to understand.
Alternatives
You could use generic exceptions and rely on error codes or messages to differentiate between different error conditions. However, custom exceptions provide a more structured and type-safe approach.
Pros
Cons
FAQ
-
Can I add custom attributes to my custom exception classes?
Yes, you can add custom attributes to your custom exception classes to store additional information about the error condition. -
Can I inherit from multiple exception classes?
Yes, you can use multiple inheritance to create custom exceptions that inherit from multiple exception classes.