Course contentsLesson 10 of 13← Course overview
  1. 01Meet Python12 min
  2. 02Set up and run Python12 min
  3. 03Variables and data types15 min
  4. 04Strings and input15 min
  5. 05Decisions with conditionals15 min
  6. 06Repeat work with loops15 min
  7. 07Functions and return values18 min
  8. 08Work with lists16 min
  9. 09Dictionaries and tuples16 min
  10. 10Understand errors and exceptions14 min
  11. 11Read and write files16 min
  12. 12Modules and the standard library14 min
  13. 13Build a small data summary20 min

Python & data · Lesson 10

Understand errors and exceptions

Edit lesson

Read an error message and handle an expected failure without hiding unrelated problems.

14 minProgress saves on this device
In this lesson
  • Distinguish syntax errors from exceptions
  • Read a traceback
  • Handle an expected exception

Helpful background: Understand variables, input, and conditionals.

Read the traceback

A syntax error means Python cannot interpret the code as written, often because punctuation or indentation is wrong. An exception is raised while a syntactically valid program is running.

A traceback shows the chain of calls leading to an exception. Start with the final line for the exception type and message, then look for the relevant line in your own code.

Handle an expected failure

Use try around the operation that may fail and catch the specific exception you can handle. int() raises ValueError when the string is not a valid integer.

Keep the try block small. Catching every exception can hide an unrelated programming error.

Handle invalid numeric textpython
text = "many"
try:
    count = int(text)
except ValueError:
    print("Enter a whole number.")
else:
    print(f"Count: {count}")

Use finally for cleanup

A finally block runs as execution leaves the try statement, including when an exception occurs. It can be useful for cleanup, but a context manager such as with is usually clearer for files.

Handling an error should leave the program in a sensible state or explain what the person can do next.

Practice debugging

Reproduce the problem with the smallest input you can, inspect the values involved, and change one thing at a time. Re-run both the failing example and a case that was already working.

Knowledge check

Which exception does int("many") raise?

Try first; feedback appears after you check.
Apply it

Your turn

Convert a text value to an integer. If it is invalid, print a helpful message.

BUILT TOGETHER

Help make this explanation better.

Have a clearer explanation, a useful example, or a correction? Share it with the community.

Contributors

Be the first to add your name when you improve this lesson.

How to get credited
Previous lessonNext lesson