# 1. Inherit from the base Exception class
class InsufficientBalanceError(Exception):
"""Raised when a withdrawal amount exceeds the account balance."""
def __init__(self, balance: float, amount: float):
self.balance = balance
self.amount = amount
super().__init__(f"Attempted to withdraw ${amount} but only have ${balance}")
# 2. Raise the custom exception in business logic
class BankAccount:
def __init__(self, balance: float):
self.balance = balance
def withdraw(self, amount: float):
if amount > self.balance:
raise InsufficientBalanceError(self.balance, amount)
self.balance -= amount
print(f"Successfully withdrew ${amount}")
# 3. Catch the custom exception
account = BankAccount(100)
try:
account.withdraw(150)
except InsufficientBalanceError as error:
print(f"Transaction Failed: {error}")
print(f"Shortage Amount: ${error.amount - error.balance}")