LevelJar Sign in

Python course / Working Python

Errors and exceptions

Read a traceback, catch the failure you expected, and raise one a caller can act on. Real input breaks programs, and how yours fails is part of how well it is written.

  • tracebacks
  • try and except
  • else and finally
  • raising
  • your own exceptions
  • where to catch
  • cleanup
  • retries

Start this module

Runs in your browser. Start straight away; create an account when you want your progress kept.

catch what you expected, refuse the rest
def portion(total, people):
    if people <= 0:
        raise ValueError(f"people must be positive, got {people}")
    return total / people


for people in [4, 0]:
    try:
        print("each gets", portion(10, people))
    except ValueError as failure:
        print("refused:", failure)
each gets 2.5
refused: people must be positive, got 0

What you will learn

The lessons in this module

  • Two kinds of error
  • Reading a traceback
  • Catching one thing
  • else and finally
  • Raising with a message
  • Catching too much
  • The ones you meet most
  • Checking first, or trying
  • One error caused by another
  • An exception of your own
  • Where to catch it
  • When not to catch
  • assert is not validation
  • Errors as values
  • Cleaning up after a failure
  • Trying again
  • Failing before you change anything
  • Following a traceback down
  • What except Exception misses
  • Messages people can act on
  • A reader that survives its data
  • Module review: the step machine

Ready when you are

Start this module

Previous: Functions. Next: Files and the filesystem. All modules are on the course page.