Raising errors#

You will have noticed, when you run code sometimes your will run some code with a mistake in it, getting an error. For example, below I have passed a list object to the math.sqrt function, resulting in a TypeError because the math library can only operator on single values, not lists.

from math import sqrt

a = [0, 1, 2, 3]

sqrt(a)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[1], line 5
      1 from math import sqrt
      3 a = [0, 1, 2, 3]
----> 5 sqrt(a)

TypeError: must be real number, not list

These errors can be very informative about how we can fix order code. In addition to ensuring that the functions used are used appropriately.

In our own functions, we can raise our own errors, using the syntax shown below.

def kelvin_to_celsius(kelvin):
    """
    Convert from Kelvin to Celsius
    
    Args:
        kelvin (float): Temperature in K
    
    Returns: 
        (float): Temperature in C
    """
    if kelvin < 0:
        raise ValueError("An unphysical temperature")
    else:
        return kelvin - 273.15

This means that if we pass a negative temperature to the above function, our error will be raised.

kelvin_to_celsius(373.15)
100.0
kelvin_to_celsius(-10)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-8-ad0bc8723e52> in <module>
----> 1 kelvin_to_celsius(-10)

<ipython-input-6-65a6760582d9> in kelvin_to_celsius(kelvin)
     10     """
     11     if kelvin < 0:
---> 12         raise ValueError("An unphysical temperature")
     13     else:
     14         return kelvin - 273.15

ValueError: An unphysical temperature

We can also raise an error if something is of the wrong type. For example.

def kelvin_to_celsius(kelvin):
    """
    Convert from Kelvin to Celsius
    
    Args:
        kelvin (float): Temperature in K
    
    Returns: 
        (float): Temperature in C
    """
    if type(kelvin) != int and type(kelvin) != float:
        raise TypeError("The temperature should be a number")
    elif kelvin < 0:
        raise ValueError("An unphysical temperature")
    else:
        return kelvin - 273.15
kelvin_to_celsius('hello')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-10-6c981ffa63b6> in <module>
----> 1 kelvin_to_celsius('hello')

<ipython-input-9-f18cbabde3b5> in kelvin_to_celsius(kelvin)
     10     """
     11     if type(kelvin) != int and type(kelvin) != float:
---> 12         raise TypeError("The temperature should be a number")
     13     elif kelvin < 0:
     14         raise ValueError("An unphysical temperature")

TypeError: The temperature should be a number

This can also be written in a more “Pythonic fashion”.

def kelvin_to_celsius(kelvin):
    """
    Convert from Kelvin to Celsius
    
    Args:
        kelvin (float): Temperature in K
    
    Returns: 
        (float): Temperature in C
    """
    if not isinstance(kelvin, int) and not isinstance(kelvin, float):
        raise TypeError("The temperature should be a number")
    elif kelvin < 0:
        raise ValueError("An unphysical temperature")
    else:
        return kelvin - 273.15

There are a wide variety, but some of the more common are detailed in the table below.

Error

Context

IndexError

Trying to access an invalid index

ModuleNotFoundError

Trying to import a non-existent module

TypeError

Acting on an inappropriate data type

ValueError

Value is inappropriate

NameError

Object with given variable name could not be found

ZeroDivisionError

Trying to divide something by zero

You will notice in the example above, we included a string that describes the cause of the error that has been thrown. These are incredibly important for ensuring the usability of your code.