Handling errors#

Programming for Geoscientists Data Science and Machine Learning for Geoscientists

When an error occurs in Python, an exception is raised.

Error types#

The full list of built-in exceptions is available in the documentation.

For example, when we create a tuple with only four elements and want to print the 5th element, we get this error message:

    flower_names = ("iris", "poppy", "dandelion", "rose")


    IndexError                                Traceback (most recent call last)
    <ipython-input-2-3497b57dd596> in <module>
          4                 "rose")
    ----> 6 print(flower_names[4])

    IndexError: tuple index out of range

IndexError refers to incorrect index, such as out of bounds.

Raising errors#

In-built functions trigger or raise errors in Python. We can do that as well by using raise:

    raise ValueError

    ValueError                                Traceback (most recent call last)
    <ipython-input-5-e4c8e09828d5> in <module>
    ----> 1 raise ValueError


Catching errors#

Try and except blocks#

To handle errors in the code gracefully, we can use try and except blocks to avoid unnecessary crashes of the program. The try block executes the program and if the program fails, exception is raised and we can recover from the error. This is especially useful if we do not want our program to crash (imagine YouTube crashing!). The syntax is:

        # some code
    except ExceptionName1:
        # code to be executed if ExceptionName1 is raised
    except ExceptionName2:
        # code to be executed if ExceptionName2 is raised
        # lines to execute if there was an exception not caught above
        # lines to execute if there was no exception at all

else is optional, at least one except needs to be raised. An example code below:

a = "ten"

# Try to create a number out of a string
# Raise an error if characters are not numbers    
except ValueError:
    print("ValueError.\nPlease use digits in your string.")
Please use digits in your string.


  • Identify which errors will be thrown in the following code samples (without running it!):

s += 1
s = [1,0,1,3,2,4]
"str" + 7

  • Types are gone! Say we have a list:

        l = [1, True, 4, "blob", "boom", 5, 6, print]

Compute the sum of the numerical elements of the list (do not use the type() function!). Is the sum what you expected? Do you notice anything interesting regarding the boolean constants?

HINT: Consider using a pass statement in the except block which circumvents (ignores) the raised error and continues the execution.