Built-in exceptions cover general problems. For errors specific to your application, such as “insufficient balance” in a banking program or “not eligible” in an admission system, you can define your own exception classes. Callers can then catch exactly those errors by name.
Defining an exception class
Two common forms
class InsufficientBalanceError(Exception): pass # message comes from raise ... ("text")class InsufficientBalanceError(Exception): def __init__(self, balance, amount): super().__init__(f"balance {balance} is less than {amount}") self.balance = balance # extra data for the handler self.amount = amount
Steps:
Define a class that inherits from Exception; by convention its name ends in Error.
Raise it where the problem is detected: raise InsufficientBalanceError(...).
Catch it by name where you can respond: except InsufficientBalanceError as e:.
Calling super().__init__(message) stores the message so that str(e) and tracebacks show it. Related exceptions can share a base class (for example BankError), so one except BankError: catches them all.
Key takeaways
Create a custom exception with class MyAppError(Exception):, choosing a new name ending in Error.
Raise it with raise, catch it with except by name.
Pass the message to super().__init__() and store extra data as attributes.
A common base class lets one handler catch a family of related errors.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Define an exception InsufficientBalanceError that stores the balance and the requested amount, raise it from a withdraw function, and handle it by printing how much more money is needed.
Show worked answer
class InsufficientBalanceError(Exception): with def __init__(self, balance, amount): super().__init__(f"balance {balance} is less than {amount}"); self.balance = balance; self.amount = amount. Then def withdraw(balance, amount): if amount > balance: raise InsufficientBalanceError(balance, amount) and return balance - amount. Handle: try: withdraw(500, 800) with except InsufficientBalanceError as e: print(e, "- need", e.amount - e.balance, "more"), which prints balance 500 is less than 800 - need 300 more.
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-201/exception-handling-in-python-programming/user-defined-exceptions/ to read this page.