Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Exceptions and traceback

Exceptions and try, except syntax

Exceptions and errors are common in all codes. There is a good system to handle them in Python. Let’s first see the following code, which gives an error despite being syntactically correct. Let’s consider that these two variables are defined:

letters = "abc"
i = 3

and then, one calls:

print(letters[i])

When this line is executed, Python stops its execution and print a traceback:

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-30-8df9cec1a0ec> in <module>()
----> 1 print(letters[i])

IndexError: string index out of range

Handling exception:

try:
    print(letters[i])
except IndexError as e:
    print(f"An IndexError has been raised and caught (message: '{e}')")
The history saving thread hit an unexpected error (OperationalError('attempt to write a readonly database')).History will not be written to the database.
An IndexError has been raised and caught (message: 'string index out of range')

We computed the average value of a list of numbers in a previous exercise. The following code seems innocuous

numbers = [1, 2]
avg0 = sum(numbers) / len(numbers)

Except in the edge case when you apply it to an empty list. try and except is a good way to avoid errors in your code

numbers = []
try:
    avg0 = sum(numbers) / len(numbers)
except ZeroDivisionError:
    print("Cannot compute average of empty list")
Cannot compute average of empty list

Full syntax

try:
    ...
except <exception1> as e1:
    ...
except <exception2> as e2:
    ...
else:
    ...
finally:
    ...

Non exhaustive error list:

Solution to Exercise 1
split_list = []
for value in str_variables.split():
    try:
        value = float(value)
    except ValueError:
        print(value, "is not a number")
    split_list.append(value)


print(split_list)
hello is not a number
['hello', 1.5, 2.0]