Exceptions

Exceptions#

Python raises exceptions when it encounters an error. The idea is that you can trap these exceptions and take an appropriate action instead of causing the code to crash. The mechanism for this is try / except. Here’s an example that causes an exception, ZeroDivisionError:

a = 1/0
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
Cell In[1], line 1
----> 1 a = 1/0

ZeroDivisionError: division by zero

and here we handle this

try:
    a = 1/0
except ZeroDivisionError:
    print("warning: you divided by zero")
    a = 1

a
warning: you divided by zero
1

another example—trying to access a key that doesn’t exist in a dictionary:

dict = {"a":1, "b":2, "c":3}
print(dict["d"])
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
Cell In[3], line 2
      1 dict = {"a":1, "b":2, "c":3}
----> 2 print(dict["d"])

KeyError: 'd'

KeyError is the exception that was raised. We can check for this and take the appropriate action instead

try:
    val = dict["d"]
except KeyError:
    val = None

print(val)
None

We haven’t talked about I/O yet, but as you might expect, when you open a file, you get an object which you can then interact with. Here we try to open a file for reading that does not already exist.

try:
    f = open("file.txt", "r")
except IOError:
    print("error: that file does not exist")
error: that file does not exist

There are a lot of different types of exceptions that you can catch, and you can catch multiple ones per except clause or have multiple except clauses. You probably won’t be able to anticipate every failure mode in advance. In that case, when you run and your code crashes because of an exception, the python interpreter will print out the name of the exception and you can then modify your code to take the appropriate action.