Exceptions · 15 min

Read tracebacks and diagnose bugs

Distinguish invalid syntax, runtime errors, and incorrect results.

Jump to the automation lab

A SyntaxError means Python could not parse the program. A missing colon after if is one example. A runtime error happens after parsing, such as a NameError when a variable is misspelled or a ZeroDivisionError when a denominator is zero.

Read the last line of a traceback for the exception class and message. Among the frames above it, start with the lowest frame that points to your own code. A logic error can produce the wrong answer without a traceback. Use a small, known input to find it.

Follow the example

A zero count reaches the function.

Run the example and practice

Make unit_price return None when count is zero. Print the results of unit_price(24, 6) and unit_price(24, 0) with no outer exception handler.

Target output

4.0
None
Show a hint

Check count before dividing. The function can return early for the zero case.

Output

Ready

Run your code to see the output here.

Check output also tests your code with additional cases.

The first run downloads Python. Code runs in your browser. Progress and drafts are stored on this device.

Show one solution
def unit_price(total, count):
    if count == 0:
        return None
    return total / count

print(unit_price(24, 6))
print(unit_price(24, 0))

Automation lab

Find a malformed stock entry

An imported count contains a word. Capture the traceback so the team can locate the conversion that failed.

Output

Ready

Run the example to see the output here.

Find the frame pointing to units_on_hand. Then try passing "12".

Further reading in Automate the Boring Stuff with Python by Al Sweigart