Skip to content

Handle errors deliberately

I can catch the exceptions a piece of code can actually raise, let the rest propagate, and raise my own with a message that tells the caller what to do.

Domain
Python Programming
Level
intermediate
Status
draft · v0.1.0
Also called
Exceptions, try except, Error handling, Raising exceptions
License
CC BY-SA 4.0

Learn first

Learn it

Scope

Deciding what a piece of code should do when the thing it depends on fails, and saying so in code.

In scope: catching specific exceptions, letting others propagate, else and finally, raising with a useful message, and defining an exception type when the standard ones do not fit. Out of scope: logging configuration and retry strategies.

Catch what you can answer

An except clause is a claim that you know what to do about that failure. If you cannot answer it here, let it travel: the caller may know, and if nobody does, the traceback is a better outcome than silence.

That makes the specific exception type the whole point. except FileNotFoundError says the file might be missing and here is the fallback. except Exception says nothing, and it will also swallow the typo in the line below — the bug you most wanted to see.

What else and finally are actually for

  • else runs only if the try block did not raise. It keeps the risky line alone in the try, so the success path is not accidentally inside the protection.
  • finally runs whatever happened, including on the way out via an exception or a return. It is for releasing what must be released. A with statement is usually the better version of the same intent.

Raising well

An exception is a message to whoever called you. raise ValueError(f"expected a positive count, got {count}") tells them what was wrong and what value did it. Returning None instead pushes the failure downstream, where it surfaces as an AttributeError far from the cause.

Define your own exception class when callers need to distinguish your failure from everyone else’s. One class inheriting from Exception is usually enough; a hierarchy is rarely earned.

Common misconceptions

  • “Robust code catches everything.” Catching everything is how a program keeps running while producing wrong answers. The robust version fails loudly and early.
  • “An exception is a performance problem.” Exceptions are ordinary in Python; asking forgiveness rather than permission is the idiomatic style for things that usually work.
  • “finally runs after return, so it cannot matter.” It runs during the return, and can change what is returned. That is a trap worth seeing once.
  • “Catching an error means handling it.” Printing it and continuing is neither.

Notes for teachers

Give learners a script wrapped in try: ... except: pass that silently produces a wrong answer, and ask them why it is wrong before showing the fix. The habit to build is asking “what would I do about this?” before writing an except.

Resources

ResourceKindCostProvider
The Python Tutorial: errors and exceptionsreadingfreePython Software Foundation
Automate the Boring Stuff, chapter 3: functions, including exception handlingreadingfreeAl Sweigart

Courses that include it

draft

Python for a Coding Assessment

A refresher path through the Python graph for someone who has written Python before and has an assessment coming: run and read, rebuild the core, then work the way an assessment expects.

Prove it

Evidence of mastery

  • Wraps an operation that can fail in a try block that catches the specific exception it raises, not every exception.
  • Explains what a bare `except:` hides, and rewrites one to catch what it meant.
  • Raises an exception with a message naming the offending value, and says why that beats returning None.
  • Uses `else` and `finally` for their actual purposes, and says what each guarantees.

Assessments that measure it

project

Python Take-Home Task

A timed take-home in the shape real hiring uses: read messy data, compute a result, test it, and hand over a repository someone else can run.

Credentials that include it

draft

Python Problem Solving

The holder can take an unfamiliar problem, write a tested Python solution someone else can run, and explain what it costs.

What learners show

Nothing to show yet. The publisher last published on 2026-09-20, and no aggregate for this outcome has reached the 50 learners a number needs. Open Degree does not track learners. About learner evidence.

What comes next