Nishaglobal Education logo

Handling errors and reading tracebacks

Read Python tracebacks to find the cause of a bug, recognise the most common error types, and handle problems gracefully with try and except.

Lesson 13 of 1430 minQuiz: 4 questions

🎯 By the end of this lesson you will be able to:

  • Read a traceback and find the line and cause of an error
  • Recognise the six most common Python errors
  • Use try and except to recover from bad input and missing files
Outline
  1. What you'll learn and why it matters
  2. Reading a traceback
  3. The errors you will meet most
  4. Catching errors with try and except
  5. Worked example: ask until the input is valid
  6. Handling more than one kind of error
  7. Practice
  8. Common mistakes
  9. Recap
  10. Quiz
  11. Mark lesson complete

What you'll learn and why it matters

Every programmer sees errors every day. The difference between a beginner and an experienced programmer is not fewer errors; it is knowing how to read them and fix them quickly. In this lesson you learn to read Python's error messages, and to make your programs cope with problems instead of crashing.

Reading a traceback

When Python hits a problem it cannot handle, it stops and prints a traceback: a report of where it was and what went wrong. Here is a program with a bug, and what Python shows:

prices.py
prices = [120, 90, 450]
total = 0
for price in prices:
    total = total + price
print("Total: " + total)
What Python shows
Traceback (most recent call last):
  File "C:\Users\asha\python-course\prices.py", line 5, in <module>
    print("Total: " + total)
          ~~~~~~~~~~^~~~~~~
TypeError: can only concatenate str (not "int") to str

Read a traceback from the bottom up:

LineWhat it tells you
TypeError: can only concatenate str (not "int") to strWhat went wrong. The first word is the error type; the rest explains it.
print("Total: " + total) with ~~~^~~~ marksThe exact code that failed. The marks point at the problem part.
File "...prices.py", line 5Where: the file and line number. Go to that line first.

So: on line 5 we tried to join text and a number with +. The fix, from lesson 4, is an f-string: print(f"Total: {total}").

The errors you will meet most

ErrorUsually meansExample cause
SyntaxErrorPython cannot read the line at allMissing colon, bracket or quotation mark
IndentationErrorSpaces at the start of a line are wrongNo indent after if, or a stray extra space
NameErrorA name is not defined (yet)Typo in a variable name, or using it before creating it
TypeErrorAn operation got the wrong type of value"Total: " + 5, or calling a function with the wrong number of arguments
ValueErrorRight type, but an unusable valueint("hello")
IndexError / KeyErrorAsking for an item that is not thereitems[10] on a 3-item list; d["missing"]
FileNotFoundErrorThe file is not where Python lookedData file in a different folder
ZeroDivisionErrorDividing by zerototal / count when count is 0

Errors that happen while the program runs (everything except SyntaxError and IndentationError) are called exceptions. You can catch exceptions.

Catching errors with try and except

Put code that might fail inside try:. If an exception happens, Python jumps to the matching except block instead of crashing:

Python
text = input("How many tickets? ")
try:
    tickets = int(text)
    print(f"Booking {tickets} tickets.")
except ValueError:
    print(f"'{text}' is not a whole number.")
print("Thank you.")

Output (you type: two)

How many tickets? two
'two' is not a whole number.
Thank you.
try:tickets = int(text)no errorValueErrorrest of try runsexcept is skippedexcept ValueError:print a friendly messageprogram carries onprint("Thank you.")
Python runs the try block. If it finishes, except is skipped. If a matching error happens, Python jumps straight to except, then carries on after it.

Name the error type you expect, such as except ValueError:. That way, other unexpected bugs still show up instead of being hidden.

Worked example: ask until the input is valid

Combine try/except with the while True loop from lesson 9 and you get input that never crashes:

Python
def ask_number(prompt):
    while True:
        try:
            return float(input(prompt))
        except ValueError:
            print("Please type a number, like 250 or 99.50.")

amount = ask_number("Amount: ")
print(f"Saved {amount:.2f}")

Output (you type: fifty, 50)

Amount: fifty
Please type a number, like 250 or 99.50.
Amount: 50
Saved 50.00

If float() works, return hands the number back and ends the loop. If it fails, except prints a hint and the loop asks again. You will reuse this function in your final project.

Handling more than one kind of error

Python
def safe_average(filename):
    try:
        with open(filename) as file:
            numbers = [float(line) for line in file]
        return sum(numbers) / len(numbers)
    except FileNotFoundError:
        print(f"Could not find {filename}.")
    except ZeroDivisionError:
        print(f"{filename} is empty.")
    except ValueError:
        print(f"{filename} has a line that is not a number.")

safe_average("does_not_exist.txt")

Output

Could not find does_not_exist.txt.

[float(line) for line in file] is a list comprehension: a one-line way to build a list with a loop. It means “make a list of float(line) for every line in the file”.

Practice

Guided exercise

Safe division

Ask for two numbers and print the first divided by the second. Handle a ValueError (not a number) and a ZeroDivisionError with friendly messages.

  1. Put both float(input(...)) calls and the division inside try:.
  2. Add except ValueError: and except ZeroDivisionError: blocks.
  3. Test it with 10 and 4, then with 10 and 0, then with ten.
Show the solution
Solution
try:
    a = float(input("First number: "))
    b = float(input("Second number: "))
    print(f"Answer: {a / b}")
except ValueError:
    print("Please type numbers only.")
except ZeroDivisionError:
    print("You cannot divide by zero.")

Output (you type: 10, 0)

First number: 10
Second number: 0
You cannot divide by zero.

How to get there: The example shows the run with 10 and 0. With 10 and 4 it prints Answer: 2.5; with ten the ValueError branch runs.

Your turn

Fix the bug

This program should print Average: 85.0 but crashes. Run it, read the last line of the traceback, then fix it.

Starter code
scores = [80, 90]
print("Average: " + sum(scores) / len(scores))
Show the solution
Solution
scores = [80, 90]
print(f"Average: {sum(scores) / len(scores)}")

Output

Average: 85.0

How to get there: The traceback ends with TypeError: can only concatenate str (not "float") to str. Joining text and a number with + is not allowed; an f-string fixes it. This is a bug to fix, not an exception to catch, so try is not the right tool.

Common mistakes

Reading the traceback from the top

You see: You look at the wrong line and feel lost

Fix: Start at the last line (the error type and message), then the line number above it.

Catching everything with a bare except:

You see: The program silently does the wrong thing and real bugs are hidden

Fix: Name the specific error: except ValueError:.

Using try/except to hide a bug

You see: The same crash comes back in another form

Fix: Fix bugs in your code. Use try for problems outside your control: user input, missing files, network failures.

Putting too much code in try

You see: It is unclear which line failed

Fix: Keep only the lines that can raise the expected error inside try.

Recap

  • Read tracebacks from the bottom: error type and message, then the file and line number.
  • Learn the common errors: SyntaxError, IndentationError, NameError, TypeError, ValueError, IndexError/KeyError, FileNotFoundError.
  • try/except ErrorType lets a program recover instead of crashing.
  • Combine try with while True to keep asking until input is valid. Catch only errors you expect.

Key terms

Traceback
Python's report of where an error happened and what it was.
Exception
An error that happens while a program runs, which can be caught with try/except.
List comprehension
A one-line way to build a list: [expression for item in collection].

Check your understanding

Answer all 4 questions, then check your answers to see an explanation for each one.

  1. 1. Which part of a traceback should you read first?

  2. 2. `int("12.5")` fails. Which error is it?

  3. 3. What does this print if the user types abc? try: n = int(input()) print("ok") except ValueError: print("bad")

  4. 4. Why is a bare `except:` with no error type a bad idea?

Answer all 4 questions to check.

Mark this lesson complete

Finished this lesson?

When you have worked through the examples and exercises, mark it complete to save your progress.