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 raised
Here’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
try
block’s statements are running, Python jumps back to thetry
and runs the statements under the firstexcept
clause that matches the raised exception. Control continues past the entiretry
statement after theexcept
block runs (unless theexcept
block raises another exception).If an exception happens in the
try
block ...
Get Learning Python now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.