Home › Learn › Python › Errors, classes, and a project

Raising errors

Lesson 37 of 40. Refuse bad input loudly with raise.

raise ValueError("amount must be positive") stops the function and hands the caller an error with a message. Raising is the right response to input a function cannot do anything sensible with; returning a made-up value hides the problem and it surfaces later, somewhere confusing. The caller decides whether to catch it.

Pick the built-in error that fits: ValueError for a value of the right type but wrong content, TypeError for the wrong type, KeyError or LookupError for missing things. You can define your own with class InsufficientFunds(Exception): pass when callers need to catch one specific condition.

def sqrt(x):
    if x < 0:
        raise ValueError("cannot take the square root of a negative number")
    return x ** 0.5

try:
    sqrt(-1)
except ValueError as e:
    print("Refused:", e)

Your task

Write withdraw(balance, amount) that raises ValueError("amount must be positive") when the amount is zero or less, raises ValueError("insufficient funds") when the amount is more than the balance, and otherwise returns the new balance.

Hint 1

if amount <= 0: raise ValueError("amount must be positive")

Hint 2

Check the amount against the balance next, then return balance - amount.

Show the solution
def withdraw(balance, amount):
    if amount <= 0:
        raise ValueError("amount must be positive")
    if amount > balance:
        raise ValueError("insufficient funds")
    return balance - amount

    Runs CPython compiled to WebAssembly in this tab (12 MB download the first time, then cached); nothing is sent anywhere.