Exceptions
- try/except. A try block attempts risky work; except catches the named error class so the program answers instead of dying.
- Raising. The raise statement throws an exception upward: with a message naming exactly what was expected and what arrived.
- finally and else. The finally block always runs: cleanup lives there: and try’s else runs only when nothing was raised.
Debugging and Tracebacks
- Reading tracebacks. A traceback prints the call chain bottom-up: the last line names the error, the lines above show the road to it.
- breakpoint. Calling breakpoint() drops you into the debugger at that exact line: inspect real values instead of guessing.
- Reproduce first. The first debugging step is a reliable reproduction: a bug you can trigger on demand is already half fixed.
Designing Reliable Failure Handling
- Specific exceptions. Catch the narrowest class that matters: a bare except swallows typos and keyboard interrupts alike.
- Custom exceptions. A small hierarchy of custom exceptions lets callers handle your library’s failures precisely.
- Fail loud at boundaries. Validate at the boundary where outside data enters, and let impossible internal states crash loudly in development.
Before and after this level
- Before: Level 6: Object-Oriented Python: Classes and Objects, Inheritance, Composition and Protocols, Dataclasses and Domain Models.
- Next: Level 8: Files & Data: Files and Paths, JSON, CSV and Serialisation, Resource Management.
In the app each of these ideas is taught and then asked back, and the level ends with a checkpoint and flashcards. See Checkpoints and flashcards.
Frequently asked questions
What does Python Level 7: Errors & Debugging cover?
Exceptions, Debugging and Tracebacks, Designing Reliable Failure Handling: 3 lessons and 9 ideas.
What should I know before this level?
The level before it, Level 6: Object-Oriented Python, which covers Classes and Objects, Inheritance, Composition and Protocols, Dataclasses and Domain Models.