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
Runs in your browser. Start straight away; create an account when you want your progress kept.
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
- Find the line that failed, and the call that led to it.
- Handle the failure you expected and let everything else through.
- Refuse a call in a way the caller can act on.
- Keep the original failure attached to the one you raise.
- Put the handler where something can still be done.
- Write the sentence someone reads at three in the morning.
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
Previous: Functions. Next: Files and the filesystem. All modules are on the course page.