Custom Exception Classes
For professional applications, relying solely on built-in exceptions like ValueError can be ambiguous. It is best practice to define your own specific exception classes to make error handling clearer.
How to Create a Custom Exception
Your custom exception class should inherit from the standard Exception class or a more specific built-in exception (e.g., ValueError).
python
1. Define the custom exception class
class InsufficientFundsError(Exception): """Raised when a transaction exceeds the available balance.""" def init(self, required, available, message="Insufficient funds for transaction."): self.required = required self.available = available self.message = message super().init(self.message)
2. Use the custom exception in a function
def withdraw(balance, amount): if amount > balance: # Raise the custom exception raise InsufficientFundsError(required=amount, available=balance)
return balance - amount
3. Handle the custom exception
initial_balance = 100 try: new_balance = withdraw(initial_balance, 200) print(f"New balance: {new_balance}") except InsufficientFundsError as e: print(f"Transaction failed: {e.message}") print(f"Needed ${e.required}, only had ${e.available}.")