Raising Errors

Interact

It is possible to tell Python to generate an error. This is useful if you want to verify input to a function or stop your code running when something happens that your code does not know how to process.

Take this very simple function for example. This function is only designed to be used with numbers, so we want to make sure we dont pass a string.

def square(x):
    if isinstance(x, str):
        raise ValueError("the argument x can not be a string")
    else:
        return x**2

The function works as expected with a number:

square(10)
100

When it is passed a string it raises an error, telling the user that the argument x can not be a string.

square("aksdj")
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-3-0c38ed1bd00a> in <module>()
----> 1 square("aksdj")

<ipython-input-1-1e7b36c66a9f> in square(x)
      1 def square(x):
      2     if isinstance(x, str):
----> 3         raise ValueError("the argument x can not be a string")
      4     else:
      5         return x**2

ValueError: the argument x can not be a string

You can raise many different kinds of exception, however ValueError is generally the most useful. Other useful types of error are:

raise TypeError("This is not a number")
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-7cceb7db3229> in <module>()
----> 1 raise TypeError("This is not a number")

TypeError: This is not a number
raise FileNotFoundError("This is not a file")
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-5-b933b80c1c6d> in <module>()
----> 1 raise FileNotFoundError("This is not a file")

FileNotFoundError: This is not a file

What Type of Error?

The example above:

def square(x):
    if isinstance(x, str):
        raise ValueError("x can not be a string")
    else:
        return x**2

uses ValueError, what type of error would be more appropriate?

Solution

TypeError should be raised when the type (i.e. str, float, int) is incorrect.

Silent Errors

Not all programming errors raise an exception, some are errors in the functioning of the code. i.e. this:

def square(x):
    return x**3
square(10)
1000

This is obviously incorrect, but Python does not know any difference, it executes the code as written and returns a result.

Most logical errors or “bugs” like this are not so easy to spot! As the complexity of your code increases the odds that mistakes and errors creep in increases. The best way to detect and prevent this kind of error is by writing tests.