Skip to main content

Section 2.3 Exceptions

When something unexpected goes wrong in a program, the code may throw an exception. If your code is written to properly handle exceptions, it can report information about what went wrong, and somtimes can even gracefully recover from the problem.

Experiment with the code below. Notice that the first print() statement executes and its output is visible, but the second print() statement never runs. This is because the exception (specifically an IndexError) occurs first.

To handle exceptions, we use a try/except block. This has the following structure:

    # An indented block of one or more statements
    # Some of them might fail and throw an exception

    # If an exception occurs, Python will run the
    # statements in this indented block

# Code below here (unindented again) will run regardless
# of whether an exception occurred.

We can get information about the specific exception that occurred by defining a variable to capture the exception in:

    # An indented block of one or more statements
    # Some of them might fail and throw an exception

except Exception as e:
    # Now `e` is an Exception object, which contains
    # some information about the problem

Now let's repeat the previous example, but using a try/except block to catch the exception.

There are several things to notice about how this code runs: First, we didn't get an error message from Python itself indicating that the code had crashed. The except block is catching and handling the error.

Second, the second print() still didn't run. When an exception occurs (in this case on line 5 when we attempt the illegal list access), the program jumps straight to the except block and does not attempt to run anything else in the try block.

This example "handles" the exception by simply printing out the error message and moving on. In real code, you might want to retry the operation that failed, try a backup method, or log the error to a file so it can be examined later.