Working on a list


In a slightly more interesting example we have a list of values. We would like to divide a number by each one of the values.

As you can see one of the values is 0 which will generate and exception.

The loop will finish early.


examples/exceptions/divide_by_zero_list.py
def div(a, b):
    print("dividing {} by {} is {}".format(a, b, a/b))

a = 100
values = [2, 5, 0, 4]

for v in values:
    div(a, v)

# dividing 100 by 2 is 50.0
# dividing 100 by 5 is 20.0
# Traceback (most recent call last):
# ...
# ZeroDivisionError: division by zero

We can't repair the case where the code tries to divide by 0, but it would be nice if we could get the rest of the results as well.