Why Create Custom Exceptions?
Python has many built-in exceptions (like ValueError
, TypeError
), but sometimes you need to define your own!
Imagine you’re building a banking app, and you want a custom exception for insufficient funds. Instead of using a generic ValueError
, why not create a meaningful error like InsufficientFundsError
?
Defining a Custom Exception
Custom exceptions in Python are created by subclassing Exception
.
class InsufficientFundsError(Exception):
"""Custom exception for handling insufficient balance."""
def __init__(self, balance, amount):
self.balance = balance
self.amount = amount
super().__init__(f"Withdrawal of {amount} failed! Available balance: {balance}")
Raising a Custom Exception
You can raise your custom exception using raise
when something goes wrong.
def withdraw_money(balance, amount):
if amount > balance:
raise InsufficientFundsError(balance, amount)
balance -= amount
return balance
try:
new_balance = withdraw_money(100, 200) # Not enough funds!
except InsufficientFundsError as e:
print(f"Error: {e}")
Output:
Error: Withdrawal of 200 failed! Available balance: 100
Catching Multiple Exceptions
You can handle both built-in and custom exceptions together.
try:
new_balance = withdraw_money(50, 100) # Another insufficient funds error!
except InsufficientFundsError as e:
print(f"Custom Exception Caught: {e}")
except Exception as e:
print(f"General Exception: {e}")
Summary
Step | Action |
---|---|
Define | Create a class inheriting from Exception |
Raise | Use raise to trigger the exception |
Catch | Handle it using try-except |
With custom exceptions, your error messages become clearer, your code is easier to debug, and your programs are more professional!
0 Comments