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.
🎯 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
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 = [120, 90, 450]
total = 0
for price in prices:
total = total + price
print("Total: " + total)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 strRead a traceback from the bottom up:
| Line | What it tells you |
|---|---|
TypeError: can only concatenate str (not "int") to str | What went wrong. The first word is the error type; the rest explains it. |
print("Total: " + total) with ~~~^~~~ marks | The exact code that failed. The marks point at the problem part. |
File "...prices.py", line 5 | Where: 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
| Error | Usually means | Example cause |
|---|---|---|
SyntaxError | Python cannot read the line at all | Missing colon, bracket or quotation mark |
IndentationError | Spaces at the start of a line are wrong | No indent after if, or a stray extra space |
NameError | A name is not defined (yet) | Typo in a variable name, or using it before creating it |
TypeError | An operation got the wrong type of value | "Total: " + 5, or calling a function with the wrong number of arguments |
ValueError | Right type, but an unusable value | int("hello") |
IndexError / KeyError | Asking for an item that is not there | items[10] on a 3-item list; d["missing"] |
FileNotFoundError | The file is not where Python looked | Data file in a different folder |
ZeroDivisionError | Dividing by zero | total / 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:
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.
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:
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
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.
- Put both
float(input(...))calls and the division insidetry:. - Add
except ValueError:andexcept ZeroDivisionError:blocks. - Test it with
10and4, then with10and0, then withten.
Show the 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.
scores = [80, 90]
print("Average: " + sum(scores) / len(scores))Show the 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 ErrorTypelets a program recover instead of crashing.- Combine
trywithwhile Trueto 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. Which part of a traceback should you read first?
2. `int("12.5")` fails. Which error is it?
3. What does this print if the user types abc? try: n = int(input()) print("ok") except ValueError: print("bad")
4. Why is a bare `except:` with no error type a bad idea?
Mark this lesson complete
Finished this lesson?
When you have worked through the examples and exercises, mark it complete to save your progress.