Exception Basics
Python exceptions are a high-level control flow device. They may be
raised either by Python or by our programs; in both cases, they may
be caught by try statements. Python
try statements come in two flavors—one that
handles exceptions and one that executes finalization code whether
exceptions occur or not.
try/except/else
The try is another compound statement; its most
complete form is sketched below. It starts with a
try header line followed by a block of indented
statements, then one or more optional except
clauses that name exceptions to be caught, and an optional
else clause at the end:
try:
<statements> # run/call actions
except <name>:
<statements> # if 'name' raised during try block
except <name>, <data>:
<statements> # if 'name' raised; get extra data
else:
<statements> # if no exception was raisedHere’s how try statements work. When a
try statement is started, Python marks the current
program context, so it can come back if an exception occurs. The
statements nested under the try header are run
first; what happens next depends on whether exceptions are raised
while the try block’s statements are running
or not:
If an exception occurs while the
tryblock’s statements are running, Python jumps back to thetryand runs the statements under the firstexceptclause that matches the raised exception. Control continues past the entiretrystatement after theexceptblock runs (unless theexceptblock raises another exception).If an exception happens in the
tryblock ...
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