Chapter 34. Exception Coding Details
The prior chapter provided a quick look at exception-related statements in action. Here, we’re going to dig a bit deeper—this chapter provides fuller coverage of exception-processing syntax in Python. Specifically, we’ll explore the details behind the try, raise, assert, and with statements. Although these statements are mostly straightforward, you’ll find that they offer powerful tools for dealing with exceptional conditions in Python code.
The try Statement
First up, the try statement is how your code catches exceptions. In short, if an exception occurs while running this statement’s main block, the program jumps back to run one of the statement’s handlers and continues from there. Its handlers may be specified by except, else, finally, and except* clauses nested in the try, and separate rules apply to these clauses’ syntax, and their valid combinations.
This is a simple model on the surface, but the try statement’s handler clauses have disjoint purposes, and its rules for valid combinations mean that it comes in distinct flavors. Because of this, we’ll approach this subject by exploring the try’s common roles in isolation first and putting their pieces together later as a combined statement. This parallels the fact that try really was separate statements in Python’s dim past, but our focus here is on its unified present.
Although technically part of the try, we’ll also defer the except* clause until the next chapter, partly because it encroaches ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access