Raising Your Own

Your own functions can raise exceptions too. Use raise to reject a value that is not allowed.

def share(slices, people):
    if people <= 0:
        raise ValueError("people must be positive")
    return slices // people

try:
    print(share(8, 0))
except ValueError as error:
    print(error)

Output:

people must be positive

The raise line stops share right away, so the division never happens. The exception then goes back to the code that called the function. It keeps going back through the callers until a matching except block catches it. If nothing catches it, Python prints a traceback.

When one of Python's built-in exception types describes the problem, use it. ValueError fits a value of the right type that is not allowed, like 0 people. TypeError fits a value of the wrong type, like text where a number was expected.

In the message, say which rule was broken, like "people must be positive". This makes the problem easier to find and fix.

In the exercise, raise the required error when an age is not valid.