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 (raiseaccepts any exception class) - base exception: your family's parent, like
BankError, so oneexceptcan catch every member - message: the text you pass when you raise;
str(e)gives it back
Step by step:
class BankError(Exception): passmakes the family's parentclass LowFunds(BankError): passmakes one kind of bank errorraise LowFunds("short by 30")raises it with a messageexcept LowFundscatches only that kind;except BankErrorcatches 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 BankErroraboveexcept LowFundscatches 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 (just30), not your sentence - inheriting from
BaseException: that is the parent of KeyboardInterrupt (Ctrl+C) and SystemExit, whichexcept Exceptiondeliberately doesn't catch; inherit fromExceptionso 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 withexcept ValueErrorkeeps working
Quiz
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)class LowFunds(BankError)andclass BankError(Exception). Which except does NOT catch a LowFunds?- except ValueError
- except BankError
- except Exception
What does this print?
class BankError(Exception): pass class LowFunds(BankError): pass try: raise LowFunds("short") except BankError: print("bank") except LowFunds: print("low")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))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
Write
class TooYoungthat inherits fromValueError(so old code withexcept ValueErrorstill works), andcheck_age(age): returnageif it is 13 or more, otherwise raiseTooYoung("too young").Build a family of bank errors:
BankError(fromException), andLowFundsandFrozen, both fromBankError. Then writewithdraw(balance, amount, frozen=False): raiseFrozeniffrozen, raiseLowFundsifamountis more thanbalance, otherwise return what is left.The bank errors and
withdraware written for you (LowFundskeeps the missing amount in.short). Writesafe_withdraw(balance, amount, frozen=False): return whatwithdrawreturns; for aLowFundsreturn"top up "followed by the missing amount; for any otherBankErrorreturn"call the bank".