Python 3D Academyবাংলা

Your own exceptions: a family of errors

🌍 In real life. A bank app can fail in different ways: not enough money, a frozen account, a transfer over the daily limit. The screen that called it wants to react to each one differently ("top up 30", "call the bank"), or to any bank problem at once. A plain ValueError can't say which one happened.

The idea in one sentence: an exception is just a class, so you make a new kind of error by inheriting from Exception, and a whole family of them by inheriting from your own.

Its words:

  • exception class: a class that inherits from Exception, the usual parent for your own errors (raise accepts any exception class)
  • base exception: your family's parent, like BankError, so one except can catch every member
  • message: the text you pass when you raise; str(e) gives it back

Step by step:

  1. class BankError(Exception): pass makes the family's parent
  2. class LowFunds(BankError): pass makes one kind of bank error
  3. raise LowFunds("short by 30") raises it with a message
  4. except LowFunds catches only that kind; except BankError catches every kind in the family

Watch a LowFunds pass the except ValueError (it isn't in that family) and land in except BankError:

Why it works. except BankError asks the same question as isinstance(error, BankError) from Lesson 22.4: is this error a BankError, or one of its children? A LowFunds inherits from BankError, so it is a BankError, and the family's except catches it. It isn't in ValueError's family, so except ValueError lets it pass. Everything else comes free from Exception: the message, the traceback, and working with raise, try and except exactly like Python's own errors.

A child class can also carry extra details. Below, LowFunds takes the missing amount, builds its message with super().__init__(...) and keeps the number in self.short, so the caller can show "top up 30" without picking the message apart:

class BankError(Exception):
    pass

class LowFunds(BankError):
    def __init__(self, short):
        super().__init__(f"not enough money: short by {short}")
        self.short = short            # an extra detail the caller can use

class Frozen(BankError):
    pass

def withdraw(balance, amount, frozen=False):
    if frozen:
        raise Frozen("this account is frozen")
    if amount > balance:
        raise LowFunds(amount - balance)
    return balance - amount

for args in [(100, 30), (100, 130), (100, 10, True)]:
    try:
        print("left:", withdraw(*args))
    except LowFunds as e:             # the most specific kind first
        print(e, "| top up", e.short)
    except BankError as e:            # then any other bank problem
        print("bank problem:", e)

Mistakes and edge cases.

  • catching the parent first: except BankError above except LowFunds catches everything, so the LowFunds block never runs; put the most specific except first (Lesson 18.2)
  • forgetting super().__init__(message): without it, str(e) shows only the raw values you passed (just 30), not your sentence
  • inheriting from BaseException: that is the parent of KeyboardInterrupt (Ctrl+C) and SystemExit, which except Exception deliberately doesn't catch; inherit from Exception so your errors behave like Python's own
  • a class for every little thing: make a new class only when a caller will handle it differently; otherwise raise ValueError or TypeError with a clear message
  • reusing a built-in parent: class TooYoung(ValueError) still counts as a ValueError, so older code with except ValueError keeps working

Quiz

  1. What does this print?

    class AppError(Exception):
        pass
    
    class NotFound(AppError):
        pass
    
    try:
        raise NotFound("no such user")
    except AppError as e:
        print(type(e).__name__, e)
  2. class LowFunds(BankError) and class BankError(Exception). Which except does NOT catch a LowFunds?

    • except ValueError
    • except BankError
    • except Exception
  3. What does this print?

    class BankError(Exception):
        pass
    
    class LowFunds(BankError):
        pass
    
    try:
        raise LowFunds("short")
    except BankError:
        print("bank")
    except LowFunds:
        print("low")
  4. This child class forgot super().__init__. What does it print?

    class LowFunds(Exception):
        def __init__(self, short):
            self.short = short
    
    e = LowFunds(30)
    print(e.short, str(e))
  5. Frozen should behave like a normal error, so except Exception catches it, but this crashes instead of printing "handled". Which line is wrong?

    class Frozen(BaseException):
        pass
    
    try:
        raise Frozen("account frozen")
    except Exception:
        print("handled")

Coding tasks

  1. Write class TooYoung that inherits from ValueError (so old code with except ValueError still works), and check_age(age): return age if it is 13 or more, otherwise raise TooYoung("too young").

  2. Build a family of bank errors: BankError (from Exception), and LowFunds and Frozen, both from BankError. Then write withdraw(balance, amount, frozen=False): raise Frozen if frozen, raise LowFunds if amount is more than balance, otherwise return what is left.

  3. The bank errors and withdraw are written for you (LowFunds keeps the missing amount in .short). Write safe_withdraw(balance, amount, frozen=False): return what withdraw returns; for a LowFunds return "top up " followed by the missing amount; for any other BankError return "call the bank".