Raising Your Own Exceptions

A function that's handed a value that makes no sense should refuse it with raise and a message that says what was wrong, can name its own kind of error with a small exception class, and raises rather than returning None when carrying on would give a wrong answer.

Journeyman · Python · Updated

By

After this lesson you can

  • Raise an exception with a message that says what was wrong, and define your own exception class for a program's rules
  • Choose between raising an exception and returning None when a function can't give an answer

Key takeaways

  • raise stops a function on purpose with an exception, such as raise ValueError("..."), and the caller can catch it with try and except like any of Python's own.
  • A helpful message says what was wrong and the value that was given, so whoever reads it knows what to fix.
  • class KioskError(Exception) makes a kind of exception of your own, so callers can tell your program's rules apart from Python's errors.
  • Returning None for a bad value lets the mistake travel on and fail somewhere else. Raise when a value makes no sense, and return None only when nothing is a normal answer.

Catching Python's errors is half the job. The other half starts when you write functions other code calls: a function that's handed a value that makes no sense has to say so, loudly and clearly, or the mistake turns into a wrong answer much later, far from where it started. This lesson shows how a function refuses a bad value, and how to choose between refusing and returning nothing.

The example is the pay kiosk at Riverside Parking Garage: $4.00 an hour, never more than $24.00 a day.

A function that quietly gets it wrong

Here's the kiosk's pricing function, and a driver who typed -3:

HOURLY_RATE = 4.00
DAILY_MAXIMUM = 24.00


def parking_fee(hours):
    fee = hours * HOURLY_RATE
    if fee > DAILY_MAXIMUM:
        fee = DAILY_MAXIMUM
    return fee


print(parking_fee(2.5))
print(parking_fee(-3))
10.0
-12.0

No error, no warning: the garage now owes the driver $12. The function did exactly what it was told, and that's the problem. Nothing in it says that negative hours are impossible.

raise: stop and say what's wrong

A bank teller handed a check for "minus twelve dollars" doesn't pay out a made-up amount. They hand it back and say what's wrong with it. A function does the same with raise (read "raise"): it stops the function on purpose with an exception, the same kind of exception Python raises itself:

HOURLY_RATE = 4.00
DAILY_MAXIMUM = 24.00


def parking_fee(hours):
    if hours < 0:
        raise ValueError(f"Hours can't be negative, but got {hours}.")
    fee = hours * HOURLY_RATE
    if fee > DAILY_MAXIMUM:
        fee = DAILY_MAXIMUM
    return fee


print(parking_fee(2.5))
print(parking_fee(-3))

On Windows, from a file named fees.py (your path will be your own):

10.0
Traceback (most recent call last):
  File "C:\Users\Sam\python-course\fees.py", line 15, in <module>
    print(parking_fee(-3))
          ~~~~~~~~~~~^^^^
  File "C:\Users\Sam\python-course\fees.py", line 7, in parking_fee
    raise ValueError(f"Hours can't be negative, but got {hours}.")
ValueError: Hours can't be negative, but got -3.

The traceback now has two File lines, a trail from the call on line 15 into parking_fee, where line 7 raised. The last line says what's wrong in words a person can act on. A helpful message names the problem and the value that caused it; add what's expected when that isn't obvious.

Pick the exception whose name fits. Python's built-in exceptions include ValueError, for a value of the right type that makes no sense (negative hours), and TypeError, for a value of the wrong type (a list where a number belongs). A caller catches yours with try and except exactly as it catches Python's.

Your own exception class

The kiosk now has two different ValueErrors: one from float() when someone types two, and one from its own rule about negative hours. A caller that wants a different message for each can't tell them apart. The answer is an exception of your own, a custom exception:

HOURLY_RATE = 4.00


class KioskError(Exception):
    """A value that breaks one of the kiosk's rules."""


def parking_fee(hours):
    if hours < 0:
        raise KioskError(f"Hours can't be negative, but got {hours}.")
    return hours * HOURLY_RATE


for typed in ["2", "two", "-3"]:
    try:
        fee = parking_fee(float(typed))
    except ValueError:
        print(f"'{typed}': please type the hours as a number.")
    except KioskError as error:
        print(f"'{typed}': {error}")
    else:
        print(f"'{typed}': ${fee:.2f}")
'2': $8.00
'two': please type the hours as a number.
'-3': Hours can't be negative, but got -3.0.

class KioskError(Exception): reads "KioskError, a kind of Exception". A class describes a new kind of thing, and Classes: Blueprints for Your Own Things teaches them; an exception class needs only these lines: its name, (Exception) in parentheses, and a docstring that says when it's raised. Name it after your program, ending in Error, the way Python names its own.

You'll also see a function catch Python's vague error and raise its own clearer one in its except block: except ValueError: and then raise ValueError("Please type the hours as a number, such as 2 or 1.5.").

Raise, or return None?

Another way to refuse is to return None, Python's value for "nothing here":

def parking_fee(hours):
    if hours < 0:
        return None
    return hours * 4.00


day_total = 0
for hours in [2, -3, 1.5]:
    day_total = day_total + parking_fee(hours)
print(day_total)
Traceback (most recent call last):
  File "C:\Users\Sam\python-course\fees.py", line 9, in <module>
    day_total = day_total + parking_fee(hours)
                ~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~
TypeError: unsupported operand type(s) for +: 'float' and 'NoneType'

Two versions of parking_fee handed -3 hours: with raise, the program stops right at parking_fee with the message Hours can't be negative, but got -3; with return None, the None travels on through the loop until the line that adds up the day's total fails with a TypeError, far from the -3 that caused it

The None traveled on until something tried to add it, and the error names the adding line, not the -3 that caused it. Every caller has to remember to check for None, and the one that forgets fails somewhere else with a confusing message. A raised exception can't be forgotten: it stops right at the cause, with a message.

So raise when the value makes no sense and carrying on would give a wrong answer. Return None when "nothing" is a normal, expected answer: looking up a car by its license plate when that car isn't in the garage, say.

Do it: refuse a monthly pass that can't exist

Riverside sells monthly passes for $90 a month, for 1 to 12 months. Write the exception and the function that prices a pass and refuses one that can't exist.

  • months: how many months the pass is for, a whole number.

Your job: write the exception class KioskError, a kind of Exception, and the function pass_price(months).

  • When months is from 1 to 12, return months times MONTHLY_PRICE (90).
  • When months is less than 1 or more than 12, raise KioskError with the message A pass is 1 to 12 months, not 0., with the value of months in place of the 0.

Worked through: pass_price(3) is 3 × 90, so it returns 270. pass_price(0) raises KioskError, whose message is A pass is 1 to 12 months, not 0.

Practiced live on the lesson page: write the Python right there and check it.

Check yourself

2 questions to try on the lesson page.

So what

A function that refuses nonsense with a clear message, at the moment it sees it, turns a confusing bug far away into one line that tells you what went wrong and where.

Key terms

Related