Python Practice › Exception Handling Programs › Program 10
Custom exception class
Write a Python program with a custom InsufficientBalanceError.
Output
Declined: balance 500 is less than 800 | short by 300
Approach
- Inherit from
Exceptionand store useful details on the object.
Solution
class InsufficientBalanceError(Exception): def __init__(self, balance, amount): super().__init__(f"balance {balance} is less than {amount}") self.shortfall = amount - balance def withdraw(balance, amount): if amount > balance: raise InsufficientBalanceError(balance, amount) return balance - amount try: withdraw(500, 800)except InsufficientBalanceError as e: print("Declined:", e, "| short by", e.shortfall)Output
Declined: balance 500 is less than 800 | short by 300
Learn the concept
New to this topic? Read the lesson, then come back.