foundation Estimated learning time: 3 hCommon in syllabi

Included in at least one reviewed higher-education syllabus.

2.6 Errors, exceptions and defensive code

Your script fails with a message that says what to do next.

Before:00. Orientation & SetupUnlocks:03. Data Handling & Analysis04. Classical AI — Agents, Search & Knowledge Representation

Good error handling separates a script that fails with instructions from one that fails with a riddle, and this topic covers try and except, custom exceptions, and logging in place of print. It sits at the end of the foundations because defensive habits should form before the code grows. The named villain is the bare except — swallowing every error including the interrupt signal, hiding exactly the information the next hour of debugging needs.

Work through these

  • try/except/else/finally

    The full structure for handling failure: attempt, respond, proceed if nothing failed, and clean up regardless. Most people learn the first two and miss the value of the last two.

  • Raising and defining custom exceptions

    Signalling failure deliberately, and defining error types specific to your own program. A specific error type is what lets a caller respond to one problem without catching everything.

  • Assertions vs. validation

    Assertions state what you believe about your own code; validation checks what came in from outside. Confusing them produces programs that fail unhelpfully in production.

  • Logging instead of print

    Logging records what happened with levels and destinations, which printing does not. Replacing print statements with logging is the step from a script to a program.

Sign in to keep your progress.

Free resources

Links last checked 29 Aug 2026.

Stuck here?

Ask a mentor. A real person answers, and they can see exactly which topic you're on. Usually within a couple of working days.

Checking your session…

Topics shown in module order.