1. Concept library
  2. Python Foundations
  3. Module 7: Files and exceptions

Concept

try and except

try runs code that might fail; except catches a named error and decides what happens next. Catching the specific exception you expect keeps real bugs visible.

What a session covers

The tutor works through these with you, in conversation and code. A session ends when you have shown them, not when a video does.

  1. Explain what try, except and else each do when an error is raised or not
  2. Write code that catches a specific exception and reports it clearly
  3. Spot why a bare except hides real bugs and narrow it

In practice

A few lines that show try and except doing its job.

Python
def parse_age(text):
    try:
        age = int(text)
    except ValueError:
        return None
    else:
        return age
    finally:
        print("checked", text)

print(parse_age("41"), parse_age("old"))

The common mistake

Watch for

Writing a bare except: or except Exception: around everything. It swallows typos, missing names and keyboard interrupts along with the error you meant to handle.

What to know first

Your roadmap puts these before try and except, unless you already know them.

How it stays learned

Once a session shows you understand try and except, it comes back for review. Each review takes a minute and tells the memory model how well you still know it.

  1. Day 3First recall, while it is fresh
  2. Day 7Second, a week on
  3. Day 18Last, when it has settled

Where it leads

Topics that build on try and except.

Previous in the module← Reading and writing files
Next in the moduleContext managers →