Errors and exceptions
Errors and exceptions
Python does not return error codes. When something cannot proceed, the code raises an exception, and the exception travels up the call stack until something catches it or the program ends with a traceback. Every library you will use in this course, from json to FastAPI to the model SDKs, reports failure this way, so being fluent means two things: raising precise exceptions from your own code, and catching only what you can handle, where you can handle it.
The style this leads to is often described as "ask forgiveness, not permission". Rather than checking whether a key exists and then reading it, you read it and catch KeyError. Rather than testing whether a file exists and then opening it, you open it and catch FileNotFoundError. The check-then-act version has a gap between the check and the act; the exception version does not, and it is usually shorter.
Continue reading
Pro unlocks every video lesson, the full notes and runnable code across the Python with AI course, from the language itself to agents, MCP, Langfuse and deployment.