Exceptions and context managers
How exceptions work
When something goes wrong, Python raises an exception. If nothing catches it, the program stops and prints a traceback. Read a traceback from the bottom up: the last line is the error type and message, and the lines above it show the chain of calls that led there, ending at the exact line.
try / except / else / finally
Figure 2.2: Which blocks run when. finally always runs, so it's where cleanup goes (or use a with block, which does it for you).
Custom exceptions
A custom exception is a one-line class that names a problem in your domain:
Callers can then handle "book unavailable" differently from "typo in the ISBN". In Week 13 your agent's tools will raise errors and return the message to the LLM so it can try again. Clear, specific error messages make agents smarter.
Rules
- Catch specific exceptions. A bare
except:orexcept Exception: passswallows every error, including your own bugs, and leaves you debugging in the dark. - Don't use exceptions for normal control flow when a simple
ifis clearer. - Raise early. Check inputs at the top of a function (
if amount <= 0: raise ValueError(...)).