Signaling Invalid Requests

Lesson 47 of 54 · Python Foundations

A function can reject an input by raising an exception. The caller can then choose how to report or recover from the problem. Raising is not the same as printing: it interrupts the current path and transfers control to a matching handler, if one exists.

def remaining_credit(balance, price):
    if price < 0:
        raise ValueError("price cannot be negative")
    if price > balance:
        raise ValueError("insufficient credit")
    return balance - price

for price in [4, 12]:
    try:
        print("remaining:", remaining_credit(10, price))
    except ValueError as problem:
        print("purchase declined:", problem)
remaining: 6
purchase declined: insufficient credit

The function enforces its rule before subtracting. The caller handles a rejected purchase; the loop can then continue with another request. This example assumes a nonnegative balance and numeric values in the same currency unit. Real money normally needs an explicit precision and currency policy.

Use an appropriate built-in exception: ValueError fits a value outside an accepted range; KeyError can describe a missing mapping key. Do not silently replace an unexpected failure with a plausible value. Handling an exception inside the function is also appropriate when that function has enough context to recover; raising to the caller is not a universal rule. An expected failure is not necessarily a bug, but mishandling it can be.