5. Files, Errors & Testing
Reading Errors & Handling Crashes (try / except)
Stop fearing red error messages: learn how to read a Python traceback from the bottom up, prevent crashes with try/except, and use Python's built-in modules.
- Read Python error tracebacks from the bottom line up
- Catch expected failures cleanly with try / except without hiding bugs
- Use built-in standard library modules like datetime, random, and pathlib
Even experienced programmers see errors every single day. The difference is that experienced programmers know how to read the error message instead of guessing!
How to Read a Python Error (Start at the Bottom!)
Suppose your script stops and prints:
Traceback (most recent call last):
File "bill.py", line 2, in <module>
age = int("twenty")
ValueError: invalid literal for int() with base 10: 'twenty'Read it from the bottom line up:
- Bottom line: Tells you the Error Name (
ValueError) and why ('twenty'isn't digits thatint()can convert). - Line right above it: Tells you the exact file and line number (
bill.py,line 2) where Python stopped!
Catching Expected Mistakes (try / except)
What if your program asks for a number, and the user accidentally types "hello"? Without protection, the whole app crashes!
Use try and except as a safety net:
user_inputs = ["25", "hello", "10"]
for text in user_inputs:
try:
number = int(text)
print(f"{number} doubled is {number * 2}")
except ValueError:
print(f"'{text}' is not a valid number—skipping it.")Watch what happens on each item:
"25"→int("25")works → prints25 doubled is 50(skipsexcept)"hello"→int("hello")triggersValueError→ Python jumps straight toexcept ValueError:and prints'hello' is not a valid number—skipping it.instead of crashing!"10"→int("10")works → prints10 doubled is 20!
Common Errors & What They Mean
ValueError: Right kind of data, wrong content (int("abc"))TypeError: Mixing things that don't go together ("Age: " + 20)KeyError: Missing dictionary key (student["missing"])IndexError: List position doesn't exist (items[99])FileNotFoundError: Trying to open a file with"r"that doesn't exist yetZeroDivisionError: Dividing a number by0
Avoid writing except: all by itself—it silently hides real typos or bugs! Always specify the exact error you expect, like except ValueError: or except ZeroDivisionError:.
else, finally, and Raising Clear Errors (raise)
Two optional blocks complete Python's error-handling toolkit:
else:runs only if thetryblock succeeded without triggering an exception—keeping your success logic nicely separated from error recovery.finally:always runs at the end whether an error happened or not (perfect for closing temporary connections or printing cleanup messages).
Sometimes your own function detects impossible inputs—such as someone trying to withdraw -50 dollars. Instead of silently computing nonsense, raise a crystal-clear ValueError right away with raise:
def set_age(age: int) -> int:
if age < 0 or age > 130:
raise ValueError(f"Age {age} is out of realistic bounds (0-130).")
return ageTools Built Right Into Python (import)
Python includes dozens of ready-made toolboxes called modules that you unlock with import:
import random
from datetime import date
today = date.today()
print("Today's date:", today)
pick = random.choice(["Python", "SQL", "Git"])
print("Random study pick:", pick)Try It Yourself in the Playground
Click “Run Code” to execute this snippet right in your browser.
Mini-Challenge: Given items = ["10", "oops", "20", "bad", "5"], write a loop using try and except ValueError: that adds up only the valid numbers (10 + 20 + 5 = 35).
Quick Checkpoints
When reading a Python Traceback error message, where should you look FIRST?