Module 09 · Lesson 02
Handling Exceptions with try and except
Keep a program running when something goes wrong: catch specific exceptions with try and except, read the error with as, and use else, finally and raise in the right places.
- About 8 minutes
- Builds on earlier lessons
- 12-question quiz at the end
What you will learn
- try and except
- Handle each problem
- else and finally
- Watch Python jump to except
Plan for problems
`try` runs code that might fail. `except` says what to do if a particular problem happens.
try
Put the line that might fail inside
try:.except
except ValueError:runs only for that problem. Others still stop the program.as
except ValueError as e:keeps the exception so you can print its message.else and finally
elseruns when nothing failed.finallyruns every time.
Handling problems everywhere
Good apps expect things to go wrong and recover politely.
- Sign-up formsAsk again when the age box gets letters instead of a number.
- Game menusA wrong key press shows a hint instead of crashing the game.
- DownloadsIf a download fails, try again a few times before giving up.
- CalculatorsShow "cannot divide by zero" instead of a traceback.
The except line
This line handles one kind of problem. Tap each part to see its job.
Part 1 of 4
except:Runs only if the code in try raised a matching exception.
Catch problems before they crash
Pick an example, change it, then press Run. Say what you expect to see before you press.
Example 1 of 6Catch one
If a line in try fails with that exception, Python jumps to except instead of stopping.
Your turn: Change text to "12". Which lines run now?
text = "twelve"
try:
age = int(text)
print("Next year:", age + 1)
except ValueError:
print("Please type digits, like 12")
print("The program keeps going")Press Run to see what it prints.Watch Python jump to except
Press Step to run one line at a time. Watch the names box change.
Ready. Press Step to run the first line.
- def safe_divide(a, b):
- try:
- return a / b
- except ZeroDivisionError:
- return None
- print(safe_divide(9, 3))
- print(safe_divide(9, 0))
Output so far
Nothing printed yet.
What Python does
Python reads the program from the top. Nothing has run yet.
Names
None yet.
Quick guesses
Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.
Question 1 of 6
1.Which except block runs?
try:
print([1, 2][9])
except KeyError:
print("key")
except IndexError:
print("index")0 of 6 answered
Common try/except misconceptions
Each card is something learners often believe. Tap it to see what Python really does.
Misconception 1 of 4
Notes
Everything above, in words. Open it when you want the full explanation.
Read the notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
try:
risky()
except ValueError: # one specific exception
...
except (KeyError, IndexError) as e: # several, with the object
print(e)
else:
... # only when try succeeded
finally:
... # always
raise # re-raise inside except
raise ValueError("message") # raise your ownPress Run to see what it prints.Worked examples
Read the problem, run the code, then read why it works.
Example 1 of 2
Reading numbers from messy text
A file of temperature readings contains some broken lines. Convert what can be converted, count the bad lines and print the average of the good ones.
from pathlib import Path
Path("temps.txt").write_text("21.5\n19\nerror\n22.0\n\n-3.5\n", encoding="utf-8")
readings = []
bad = 0
for line in Path("temps.txt").read_text(encoding="utf-8").splitlines():
try:
readings.append(float(line))
except ValueError:
bad += 1
print("Good:", readings)
print("Bad lines:", bad)
print("Average:", round(sum(readings) / len(readings), 2))Press Run to see what it prints.Predict first
How it works(open after your guess)
Common pitfalls
Mistakes people make with this topic, and what to write instead.
Pitfall 1 of 3
A bare except that hides bugs
Spot the bug
Can you see what is wrong? Run it to watch it go wrong, then open the fix.
try:
total = sum(pricse)
except:
total = 0Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- Payments
Processing payments without stopping the batch
A billing job charges a list of customers each night. One broken record must not stop everyone else from being billed, but every failure must be reported for a person to check.
Why Python fits
Each customer is handled in its own try, so a failure affects only that record. Two specific excepts give precise reasons, and the else records only successful conversions. The finally block counts every customer, charged or not, the way a real system would write one audit line per record.
Pythoncustomers = [ {"id": "c1", "amount": "19.99"}, {"id": "c2", "amount": "free"}, {"id": "c3"}, {"id": "c4", "amount": "5"}, ] charged, failed = [], [] checked = 0 for customer in customers: try: amount = float(customer["amount"]) except KeyError: failed.append((customer["id"], "no amount")) except ValueError: failed.append((customer["id"], f"bad amount {customer['amount']!r}")) else: charged.append(amount) finally: checked += 1 print(f"Checked {checked}, charged {len(charged)}, total {sum(charged):.2f}") for cid, reason in failed: print("Check", cid, "-", reason)OutputPress Run to see what it prints.
Key takeaways
Tick each one you could explain to a friend.
0 of 5
Common questions
Guess the answer first, then open it.
Does try make my program slower?
Can I catch an exception from a function I called?
Should every line be inside a try?
Your notes
Sign in to keep private notes alongside this lesson.
Where to go next
The quiz and the Lab live on their own pages, so this lesson stays about learning.
Finished this lesson?
Create an ID or sign in to save your progress across devices.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
Spaced review
Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.
This lesson at a glance
The 12 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.
What else you can search for and explore
Curious to go further? Each card opens a web search in a new tab.
References
Look things up here whenever you need the exact details.