HomeCourseModule 04 › try / except — handling errors gracefully

try / except — handling errors gracefully

Module 04 · Control Flow7 min readBeginner

What you'll learn

  • Wrap risky code in try/except
  • Catch specific exception types
  • Decide when NOT to catch

The pattern

try:
    n = int(user_input)
except ValueError:
    n = 0
    print("Couldn't parse the number, defaulting to 0.")

Python runs the try block. If a ValueError is raised, control jumps to the except block. If no error, the except is skipped.

The big four exception types

Catch specific, not generic

# OK but lazy — swallows bugs you'd want to know about
try:
    do_thing()
except:
    pass

# Better — explicit about what you expect
try:
    do_thing()
except FileNotFoundError:
    print("File missing, skipping.")

The finally block — cleanup that always runs

f = open("data.txt")
try:
    work_with(f)
except Exception as e:
    print(f"Failed: {e}")
finally:
    f.close()      # runs whether we succeeded or not

Walkthrough: process a folder of CSVs that might be broken

The plan

Loop through all CSVs in a folder. Try to read each. If one is broken, log it and keep going — don't let one bad file stop the rest.

The script

import pandas as pd
from pathlib import Path

results = []
for path in Path("monthly_files").glob("*.csv"):
    try:
        df = pd.read_csv(path)
        results.append((path.name, len(df)))
    except Exception as e:
        print(f"Skipped {path.name}: {e}")

print(f"Processed {len(results)} files successfully")
⚠️ Don't catch bugs
The wrong place for try/except: hiding bugs. If your code has a typo, you want it to crash so you can fix it. Only catch errors you've thought about in advance.

Key takeaways

  • Wrap risky code (file I/O, type conversions, network calls) in try.
  • Catch specific exception types — ValueError, FileNotFoundError etc.
  • Use finally for cleanup that must always run.
  • Don't use try/except to hide bugs.

Safe parser

Write a function to_float(text) that returns a float if it can, or None if it can't. Then test it with: "12.5", "abc", "", "100".

📹 Video walkthrough
A video walkthrough of this lesson will be embedded here. Until then, the written walkthrough above mirrors what the video will cover step-for-step.