MCS-201 · Unit 14

Exception Handling in Python Programming

Section 5 of 5

Block 4 · Unit 14Exception Handling in Python Programming8 min · Section 5 of 5

14.5User-Defined Exceptions

Covers IGNOU MCS-201 §14.5

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:

  1. Define a class that inherits from Exception; by convention its name ends in Error.
  2. Raise it where the problem is detected: raise InsufficientBalanceError(...).
  3. 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 1 · multiple choice

Which class should a user-defined exception normally inherit from?

Show answer

Answer: C. Exception

Inheriting from Exception puts it with ordinary errors, so except Exception: catches it. There is no built-in class named Error.

Question 2 · multiple choice

Which keyword is NOT used for exception handling in Python?

Show answer

Answer: C. accept

accept is not a Python keyword; the exception keywords are try, except, else, finally and raise.

Question 3 · multiple choice

What does this program print?

Python · quiz_custom.py
class EmptyCartError(Exception):
    pass

def checkout(cart):
    if not cart:
        raise EmptyCartError("cart is empty")
    return len(cart)

try:
    print(checkout(["pen"]))
    print(checkout([]))
except EmptyCartError as e:
    print("Cannot checkout:", e)
Show answer

Answer: B. 1, then Cannot checkout: cart is empty

The first call returns 1; the second raises the custom exception, whose message comes from the argument passed to it.

Question 4 · multiple choice

Given class BankError(Exception) and class OverdraftError(BankError), which clause catches an OverdraftError?

Show answer

Answer: C. Either except OverdraftError: or except BankError:

An except clause catches its class and all subclasses.

Question 5 · multiple choice

Why call super().__init__(message) in a custom exception’s constructor?

Show answer

Answer: A. So the message is stored in the base Exception and shown by str(e) and tracebacks

The base class keeps the arguments in e.args, which is what str(e) and tracebacks display.

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.

↑ ↓ move↵ openTab switch type