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 the try and runs the statements under the first except clause that matches the raised exception. Control continues past the entire try statement after the except block runs (unless the except 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.