Python · Intermediate level

Intermediate level · Module 2: Error Handling and Defensive Programming · Lesson 1 of 3

Handling Exceptions

Catch specific errors so a program can recover or explain the problem instead of crashing.

In this lesson you will

  • Catch specific exception types
  • Use else and finally correctly

Key concepts

exceptionValueError/FileNotFoundErrortry/exceptfinally

The lesson

An exception is Python's way of reporting that something went wrong while the program was running: a missing file, a value that cannot be converted, a lost connection. Unhandled, it stops the program.

try/except lets you catch specific exceptions and respond sensibly — skip a bad row and report it, or show a clear message instead of a traceback. Catch the narrowest exception you expect (ValueError, FileNotFoundError) rather than a bare except, which hides real bugs.

else runs when no exception happened and finally always runs, which is useful for clean-up. Count and report what you skipped: silently ignoring bad data is worse than crashing.

Step by step

  1. Wrap the file opening in try/except FileNotFoundError.
  2. Inside the row loop, wrap the number conversion in try/except ValueError.
  3. Record the line number and reason for each skipped row.
  4. Print a summary: rows processed, rows skipped, total.
Code example

Processing a survey export without crashing

Skip and report bad rows in a CSV instead of stopping at the first problem.

Pythonclean_payments.py
import csvimport io # In real use: open("payments.csv", newline="", encoding="utf-8")data = io.StringIO(    "name,amount\n"    "Akol,15000\n"    "Mary,twelve thousand\n"    "Deng,\n"    "Nyandeng,22000\n") total = 0skipped = []for line_no, row in enumerate(csv.DictReader(data), start=2):    try:        total += int(row["amount"])    except ValueError:        skipped.append(f"line {line_no}: {row['name']} — amount '{row['amount']}'") print(f"Total received: {total:,} SSP")print(f"Skipped {len(skipped)} rows:")for reason in skipped:    print("  " + reason)

Output

Total received: 37,000 SSP
Skipped 2 rows:
  line 3: Mary — amount 'twelve thousand'
  line 4: Deng — amount ''

How it works

csv.DictReader turns each row into a dictionary. int() raises ValueError for text such as 'twelve thousand' or an empty cell, so the conversion sits inside try/except: good rows are added, bad rows are recorded with their line number (line 1 is the header) and the program carries on. The summary shows exactly what to fix in the source data.

Key concepts

try/except ValueErrorcsv.DictReaderenumerate(start=2)reporting skipped data

Where you would use it

Cleaning KoboToolbox or Excel exports where a few typed entries are always wrong.

Practice activity

Make the CSV sales script handle a missing file and a non-numeric amount without crashing, reporting the bad row number.

Expected result: The script skips bad rows with a message and finishes processing good rows.

Check your understanding

  1. Why avoid 'except:' without an exception type?

    Show answer

    It catches everything, including programming mistakes and Ctrl+C, hiding real bugs.

  2. When does a finally block run?

    Show answer

    Always, whether or not an exception occurred.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.