Module 09 · Lesson 01
Errors and Exceptions
Read Python's error messages with confidence: tell syntax errors from runtime exceptions, read a traceback from the bottom up, and recognise the common exception types and their causes.
- About 9 minutes
- Builds on earlier lessons
- 12-question quiz at the end
What you will learn
- Two kinds of error
- Read a traceback
- Name the exception
- Watch a check prevent one
When Python stops
An error is Python telling you exactly what went wrong and where. Reading it is a skill you can learn.
Two kinds
A
SyntaxErrorstops the program before it starts. An exception happens while it runs.Read the bottom
The last line of a traceback names the exception and says what went wrong.
Follow the trail
The lines above it show each call that led there, oldest first.
Prevent
Check with
in,len()or.get()before you reach for something that might be missing.
Errors everywhere
Every app meets problems. Good ones notice them and say something useful.
- Web formsLetters typed into an age box would be a
ValueErrorwithout a check. - GamesReading past the end of the level list is an
IndexError. - ContactsLooking up a name that is not saved is a
KeyError. - Crash reportsA traceback is the first thing developers read when an app crashes.
One line, four possible errors
This short line can fail in four different ways. Tap each part to see which error it could cause.
Part 1 of 5
result:Only gets a value if everything on the right works.
Meet the exceptions
Pick an example, run it, then follow its task to make Python complain. Read the last red line each time.
Example 1 of 6Read the message
A traceback ends with the exception's name and a message. This one runs fine until you change it.
Your turn: Change "Ana" to "Cy" and run. Which exception does the last red line name?
ages = {"Ana": 12, "Ben": 14}
print(ages["Ana"])
print("All fine so far")Press Run to see what it prints.Watch a check prevent an error
Press Step to run one line at a time. Watch the names box change.
Ready. Press Step to run the first line.
- scores = [8, 0, 5]
- total = 0
- for s in scores:
- if s == 0:
- print("skip zero")
- continue
- total += 10 / s
- print(round(total, 2))
Output so far
Nothing printed yet.
What Python does
Python reads the program from the top. Nothing has run yet.
Names
None yet.
Name that exception
Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.
Question 1 of 6
1.Reading past the end of a string:
print("abc"[5])0 of 6 answered
Common error 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.
SyntaxError # invalid code, found before running
NameError # unknown name
TypeError # wrong type or argument count
ValueError # right type, bad value: int("x")
IndexError # list position out of range
KeyError # missing dictionary key
ZeroDivisionError # x / 0
AttributeError # object has no such attribute
FileNotFoundError # file missing when reading
print(repr(value), type(value)) # inspect before the failing linePress Run to see what it prints.Worked examples
Read the problem, run the code, then read why it works.
Example 1 of 2
Checking before converting
A list of ages was typed by hand and some entries are not numbers. Convert only the valid ones, report the rest, and print the average age, without causing a ValueError.
entries = ["34", "twenty", "51", "", "28", "4o"]
ages = []
for entry in entries:
if entry.isdigit():
ages.append(int(entry))
else:
print(f"Skipping {entry!r}: not a whole number")
print("Valid ages:", ages)
print("Average:", round(sum(ages) / len(ages), 1))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
Joining text and a number with +
Spot the bug
Can you see what is wrong? Run it to watch it go wrong, then open the fix.
age = 30
print("Age: " + age)Press 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.
- Logistics
Validating rows before an import
A warehouse imports parcel weights from a supplier file. Before loading the rows into its system, a script checks each one and lists the problems, so the supplier can fix them instead of the import crashing halfway.
Why Python fits
Each check prevents one exception:
getavoidsKeyError, the digit test avoidsValueErrorfromfloat, and the zero test catches a value that would cause aZeroDivisionErrorlater. Collecting the problems gives one useful report instead of a crash on the first bad row.Pythonrows = [ {"id": "P1", "kg": "2.5"}, {"id": "P2", "kg": "heavy"}, {"id": "P3"}, {"id": "P4", "kg": "0"}, ] problems = [] for row in rows: kg = row.get("kg") if kg is None: problems.append(f"{row['id']}: missing weight") elif not kg.replace(".", "", 1).isdigit(): problems.append(f"{row['id']}: weight {kg!r} is not a number") elif float(kg) == 0: problems.append(f"{row['id']}: weight is zero") print(len(problems), "problems") for problem in problems: print("-", problem)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.
Why does the error point at the line after my mistake?
Is an exception always a bug?
What is the difference between an error and an exception?
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 10 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.