Custom exception class

MediumException Handling Programs · 10 of 20

Write a Python program with a custom InsufficientBalanceError.

Advertisement
Output
Declined: balance 500 is less than 800 | short by 300

Approach

  1. Inherit from Exception and store useful details on the object.

Solution

Python
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
Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More exception handling programs

← All 20 Exception Handling Programs