DSC 20 Reading · Exceptions
Starting Python…

Writing reliable programs

Exceptions

A customer types twelve where the pizza shop expected the number 12. Or asks for a size that is not on the menu. Programs meet surprises like these all the time. Python has a way of reporting these exceptional situations, and with a few keywords you can decide what happens next instead of letting the program crash.

1What is an exception?

Python can fail in two different ways. A syntax error means the code is not written in valid Python, and Python notices before running anything. An exception means the code is valid, but something goes wrong while it runs. Here is an exception. The code is fine, but dividing by zero is impossible.

The first line printed, and then the program stopped. The message is called a traceback. Read it from the bottom. The last line names the kind of exception, ZeroDivisionError, and gives a short reason. The lines above it show where in your code it happened.

A syntax error behaves differently. This cell has a missing closing parenthesis on its last line.

Notice that Starting the order never appeared. Python reads the whole cell first, finds the mistake, and refuses to run any of it. An exception, by contrast, only happens when the program reaches the bad line.

When an exception is not handled, the program stops. The rest of this chapter explains how Python handles the exceptions.

2Common exceptions

Every exception has a type, and the type tells you what kind of problem it is. These are the ones you will meet most often.

ExceptionTypical cause
ValueErrorThe right type of value, but not an acceptable one: int("twelve")
TypeErrorAn operation on the wrong type: "9" + 1
KeyErrorA dictionary key that is not there: PRICES["huge"]
IndexErrorA list position that does not exist: toppings[5]
ZeroDivisionErrorDividing by zero
NameErrorUsing a name that was never defined
AttributeErrorAsking an object for an attribute or method it does not have
FileNotFoundErrorOpening a file that does not exist

The next cell triggers one of each and prints what Python reports. It uses try and except, which the next section explains, so just run it and read the output.

Quick check
What does PRICES["huge"] raise when "huge" is not a key?

3Handling with try and except

Put the risky code in a try block, and say what to do about a particular problem in an except block. Python runs the try block. If an exception of the named type happens, Python jumps straight to the matching except block. The rest of the try block is skipped, and the program carries on after the whole statement.

The line that prints Slices never ran, because int("eight") failed first. Change "eight" to "8" and run again to see the other path.

You can keep the exception object with as. It holds the message, which is handy for reporting what went wrong. Here a function returns None instead of crashing when a size is unknown.

Catch only what you expect

You can write except: with no type, which catches everything. This is almost always a mistake, because it also hides your own bugs. Find the bug in this cell.

Show the fix

The function printed 0 and gave no sign of trouble. The real problem is the typo prises, which is a NameError, and the bare except swallowed it. Fix the typo, and remove the try, since nothing in that line needs one. If you do need a handler, name the exception you expect, such as except TypeError:, so that other mistakes still show up.

A try statement can have several except blocks, each for a different type. Python checks them from top to bottom and runs the first one that matches. Here an order is written as "size,count".

Both "large" and "large,two" lead to a ValueError. The first cannot be split into two parts, and the second has a count that is not a number. A single except ValueError handles both.

4else and finally

Two more blocks can follow except.

Predict what each of the two calls prints.

Show the answer

The first call prints With tip: 18.0 and then Done. The conversion worked, so else ran. The second call prints Not a number and then Done. The conversion failed, so except ran and else was skipped. In both calls finally ran last.

The order is always try, then except, then else, then finally.

5Raising exceptions

You can raise an exception yourself with the raise keyword. This is how a function tells its caller that it was given something it cannot work with. Pick the built-in type that fits and add a message.

The function itself does not know what to do about a bad size. It could be a typing mistake, or a request for a size you do not sell. Raising lets the code that called it decide. That code can handle the exception with try and except like any other.

assert

The assert statement checks that something you believe is true really is. If the condition is false, Python raises an AssertionError with your message.

6Practice

Exercise 1: a safe price lookup

Write get_price(size). It returns the price for that size. If the size is not on the menu, it returns None instead of crashing. Catch only the exception that a missing key causes.

Hint

Put return PRICES[size] inside a try block. Add except KeyError: and return None there.

Show a solution
def get_price(size):
    try:
        return PRICES[size]
    except KeyError:
        return None

Exercise 2: refuse a bad size

Finish the constructor of Pizza. If size is not a key of PRICES, raise a ValueError with the message unknown size: followed by the size. Otherwise set up the attributes as usual.

Hint

Check the size first, before setting anything. Use if size not in PRICES: and inside it write raise ValueError(...) with an f-string for the message. The three lines that set the attributes come after the check.

Show a solution
    def __init__(self, size, toppings):
        if size not in PRICES:
            raise ValueError(f"unknown size: {size}")
        self.size = size
        self.toppings = toppings
        self.price = PRICES[size] + len(toppings)