Skip to contentSkip to navigation

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 SyntaxError stops 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 ValueError without 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

Tap any part of the code below, or press Next.1 of 5 explored

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?

Python
ages = {"Ana": 12, "Ben": 14}
print(ages["Ana"])
print("All fine so far")
Output
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.

  1. scores = [8, 0, 5]
  2. total = 0
  3. for s in scores:
  4. if s == 0:
  5. print("skip zero")
  6. continue
  7. total += 10 / s
  8. 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 notesOpen

Two kinds of error

Python reports problems at two different moments.

A syntax error means the code is not valid Python at all: a missing colon, an unclosed bracket, a misspelled keyword. Python checks the whole file before running anything, so a syntax error stops the program before its first line runs.

Try it 1: edit me, then Run
if score > 50
    print("pass")
# SyntaxError: expected ':'
Output
Press Run to see what it prints.

An exception happens while the program is running, on code that is valid Python but cannot do what it was asked in this situation. Everything before the failing line has already run.

Try it 2: edit me, then Run
print("Starting")
print(10 / 0)
print("Never reached")
# Starting
# ZeroDivisionError: division by zero
Output
Press Run to see what it prints.

The distinction matters when you hunt for the cause. A syntax error points at a line that is badly written. An exception points at a line that is well written but met values it could not handle, so the real cause is often a few lines earlier, where those values came from.

Reading a traceback

When an exception is not handled, Python prints a traceback and stops:

Traceback (most recent call last):
  File "shop.py", line 7, in <module>
    total = add_tax(price)
  File "shop.py", line 3, in add_tax
    return price * 1.2
           ~~~~~~^~~~~
TypeError: can't multiply sequence by non-int of type 'float'

Read it from the bottom up:

  1. The last line is the most important. Before the colon is the exception type, TypeError. After it is the message, which explains what went wrong.
  2. Just above are the file, the line number and the code that failed, return price * 1.2 on line 3, often with markers pointing at the exact part.
  3. Further up is how the program got there: line 7 called add_tax. "Most recent call last" means the deepest call is at the bottom.

Here the message says a sequence was multiplied by a float. A sequence is a string or list, so price must be a string, perhaps because it came from input() and was never converted. The fix belongs on line 7 or earlier, not on line 3.

The exceptions you will meet most

Exception Typical cause Example
NameError a name that does not exist: a typo, or a variable used before it is assigned pritn("hi")
TypeError an operation on the wrong type, or a wrong number of arguments "age: " + 30
ValueError the right type with an unusable value int("twelve")
IndexError a list position that does not exist [1, 2][5]
KeyError a dictionary key that does not exist {"a": 1}["b"]
ZeroDivisionError dividing by zero total / 0
AttributeError a method or attribute the object does not have [1, 2].push(3)
FileNotFoundError opening a file that is not there for reading open("nope.txt")

The type alone narrows the search a lot. A KeyError sends you to a dictionary lookup, an IndexError to a list position, a ValueError to a conversion. The message adds the details: KeyError: 'emial' shows the misspelled key, and recent Python versions even add hints such as Did you mean: 'email'?.

A debugging routine

When a program fails, work through the same steps every time:

  1. Read the last line: which exception, and what does the message say?
  2. Find the failing line in your own code. Ignore lines inside Python's own modules at first; look for the lowest line that is in a file you wrote.
  3. Ask what values the variables on that line had. If you are not sure, add a print() just before it, such as print(repr(price), type(price)). repr shows quotes around strings, so a string that looks like a number is easy to spot.
  4. Work backwards to where the wrong value came from, and fix it there.
  5. Run again. One fix sometimes reveals the next error further on, which is progress.

Preventing exceptions

Many exceptions can be avoided by checking first: use key in dictionary or dictionary.get(key) before a lookup, check len(items) before indexing, check that a divisor is not zero, or use text.isdigit() before calling int. Python calls this style "look before you leap". The next lesson shows the other style, "easier to ask forgiveness than permission": try the operation and handle the exception if it happens. Both have their place.

Exceptions are objects

An exception is not just a message; it is an object of a class such as ValueError. Those classes form a family tree. For example, FileNotFoundError is a kind of OSError, and both IndexError and KeyError are kinds of LookupError. That tree is what lets you handle a whole group of related errors at once, which the next two lessons put to use.

Syntax

The general shape of the statements in this lesson.

syntax.py
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 line
Output
Press 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

Beginner

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.

Python
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))
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

Calling int on every entry would stop the program with ValueError at "twenty". Checking isdigit() first keeps only the convertible strings. The !r in the f-string shows the entry with quotes, so the empty string and "4o" (a letter o, not a zero) are easy to see.

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.

Buggy code: run it
age = 30
print("Age: " + age)
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

TypeError: can only concatenate str (not "int") to str

Write this instead

age = 30
print(f"Age: {age}")

Why it happens

+ joins two strings or adds two numbers, but cannot mix them.

In the real world

Where this shows up in software people use every day.

  1. Validating rows before an import

    Logistics

    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: get avoids KeyError, the digit test avoids ValueError from float, and the zero test catches a value that would cause a ZeroDivisionError later. Collecting the problems gives one useful report instead of a crash on the first bad row.

    Python
    rows = [
        {"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)
    Output
    Press 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?

For syntax errors such as an unclosed bracket, Python only notices the problem when the next line does not fit. Check the line above the one it reports.

Is an exception always a bug?

Not always. A missing file or bad user input is a normal situation that a good program should expect. The next lesson shows how to handle such cases on purpose.

What is the difference between an error and an exception?

People use the words loosely. In Python, exceptions are the objects raised at run time, and most of their class names end in Error.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

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.

Create ID to save
Lessons done in this module0/3 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

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.