Python & data · Lesson 10
Understand errors and exceptions
Read an error message and handle an expected failure without hiding unrelated problems.
- 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.
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.
Which exception does int("many") raise?
Your turn
Convert a text value to an integer. If it is invalid, print a helpful message.
text = "twelve" try: value = int(text) except ValueError: print("Please use digits.") else: print(value)
BUILT TOGETHER
Help make this explanation better.
Have a clearer explanation, a useful example, or a correction? Share it with the community.
Be the first to add your name when you improve this lesson.
How to get credited