Files, Errors and Modules · Robust Code · lesson 2 of 8
Raising and custom exceptions
about 14 minutes · free · runs in your browser
Refusing to continue
Sometimes the right answer is to fail. raise does that:
def withdraw(balance, amount):
if amount > balance:
raise ValueError("insufficient funds")
return balance - amount
Returning None or -1 for an impossible request only postpones the problem: the
caller forgets to check, and the bad value spreads. An exception cannot be ignored by
accident.
Define your own when callers need to catch your failure specifically:
class InsufficientFunds(Exception):
pass
Inheriting from Exception is all that is required. Now a caller can write
except InsufficientFunds: and leave everything else alone.
Your turn: define InsufficientFunds and write withdraw(balance, amount) that
raises it when the amount is more than the balance, and ValueError when the amount is
zero or negative.
You start from this, and edit it in the browser:
class InsufficientFunds(Exception):
pass
def withdraw(balance, amount):
# Raise for bad amounts, otherwise return the new balance.
pass