Understanding Errors and Exceptions in Python

One of the most common situations while writing code is getting stuck on an unidentifiable error. In such a case, python's ecosystem helps us to trace back our function calls with the help of traceback reports, to find out the exception raised.

Imgur

These tracebacks return the exception name and the error message along with the executed code to help us identify the reason for these exceptions being raised.

Exceptions raised simply define the type of error our program has run into. Which is why these terms are used interchangeably, but precisely mean the same.

There are a number of built-in exceptions in python library, who's awareness can help to speed up the our programming. Let's look at some of the important buit-in exceptions in python.

SyntaxError

The most common type of error in a Python program is when the user uses incorrect syntax. i.e, when a piece of code is not in accordance with its documentation.

In the code below, the variable a has been declared with its desired data type stated before the variable name, which is not how a variable is declared in Python.

int a = 2.8
a
File "<ipython-input-1-14f5aded83ca>", line 1 int a = 2.8 ^ SyntaxError: invalid syntax

The error message apprises us that there was an error in our syntax. Delving into the traceback, there is a \( ^ \) Caret symbol, that points out the location of incorrect code which caused the exception .

# Correct Code:
a = int(2.8)
a
2

Indentation Error

Indentation refers to the spaces in the begining of our code. In other programming languages, indentation is only for readability whereas in python, indentation is very important.

Python uses indentation to indicate a block of code.

for i in range(5):
print("*")
File "<ipython-input-2-105c4c607e6c>", line 2 print("*") ^ IndentationError: expected an indented block

In the above code, the missing indentation before print raises an IndentationError.

Index Error

The IndexError is thrown when we try to access an element who's index is not in the range of our iterable object.

a_list = [i for i in 'abcdefgh']
a_list[len(a_list)]
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-4-a6bff1ef6421> in <module>() 1 a_list = [i for i in 'abcdefgh'] ----> 2 a_list[len(a_list)] IndexError: list index out of range

The indexing of a list begins from zero and goes upto (n-1), where n = length of list. In the code above, we are trying to access the element at the \(nth \) index, whereas the last index is \((n-1)\).

Key Error

The KeyError is like an IndexError but for dictionaries. It is raised when we try to access an invalid/nonexistent key in the dictionary.

a_dict = {'a':1, 'b' : 2, 'c' :3}

a_dict['d']
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-8-372a1f172dda> in <module>() 1 a_dict = {'a':1, 'b' : 2, 'c' :3} 2 ----> 3 a_dict['d'] KeyError: 'd'

Import Error

This exception is raised when the parser is not able to import the module that is needed to be imported.

from numpy import mediam
--------------------------------------------------------------------------- ImportError Traceback (most recent call last) <ipython-input-4-be0dea60ada8> in <module>() ----> 1 from numpy import mediam ImportError: cannot import name 'mediam' from 'numpy' (/usr/local/lib/python3.7/dist-packages/numpy/__init__.py) --------------------------------------------------------------------------- NOTE: If your import is failing due to a missing package, you can manually install dependencies using either !pip or !apt. To view examples of installing some common dependencies, click the "Open Examples" button below. ---------------------------------------------------------------------------

Now, there is no numpy.mediam function in the numpy library. Instead the correct function is numpy.median which is why we got the ImportError.

ModuleNotFoundError

This is a subclass of ImportError. It is raised when the module we are trying to import cannot be located.

import wrongmodule
--------------------------------------------------------------------------- ModuleNotFoundError Traceback (most recent call last) <ipython-input-5-1160ccc1fb60> in <module>() ----> 1 import wrongmodule ModuleNotFoundError: No module named 'wrongmodule' --------------------------------------------------------------------------- NOTE: If your import is failing due to a missing package, you can manually install dependencies using either !pip or !apt. To view examples of installing some common dependencies, click the "Open Examples" button below. ---------------------------------------------------------------------------

Because wrongmodule is a made up module/library, we get the exception ModuleNotFoundError.

Name Error

The NameError is raised when we call an undefined variable, class or function locally or globally.

print(a)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-9-bca0e2660b9f> in <module>() ----> 1 print(a) NameError: name 'a' is not defined

Attribute Error

An AttributeError is thrown when we access that attribute on an object which it doesnt have defined.

For example in the code below, we are trying to access the length attribute of an instance of Frame class. But because there is no such attribute as length defined, we get an AttributeError.

class Frame:
  count = 0
  def __init__(self, breadth = 15):
    Frame.count +=1

frame1 = Frame()
frame2 = Frame(breadth=20)

frame2.length
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-3-743aa5d02062> in <module>() 7 frame2 = Frame(breadth=20) 8 ----> 9 frame2.length AttributeError: 'Frame' object has no attribute 'length'

Value Error

A value error is raised when an operation in python is given the right type of argument but an inappropriate value.

This can be considered a more generic case of IndexError. Where an element is being accesed but is not present. Or visa versa.

Let's look at some examples of value error.

a,b = 2,4,6
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-7-ff438f317ff0> in <module>() ----> 1 a,b = 2,4,6 ValueError: too many values to unpack (expected 2)
float('abc')
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-8-1d9e98dc2a69> in <module>() ----> 1 float('abc') ValueError: could not convert string to float: 'abc'

Type Error

A TypeError is thrown when a python function/operation is applied to an object of inappropriate datatype. For example, adding two strings.

sum('a','b')
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-8-6bee6b900189> in <module>() ----> 1 sum('a','b') TypeError: sum() can't sum strings [use ''.join(seq) instead]
def function_name():
  print('a')

function_name(1)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-4-6c1ac4e6b6a6> in <module>() 2 print('a') 3 ----> 4 function_name(1) TypeError: function_name() takes 0 positional arguments but 1 was given
 

Conclusion

To get hold of your python errors, it is important to delve into tracebacks and built-in exceptions. There are a bunch of inbuilt exceptions we haven't talked about here, but you can find in the python documentary.

Exception handling is one such technique to get passed these errors without letting your code terminate in the middle. More on that later.

# Execute this to save new versions of the notebook
jovian.commit(project="python-common-errors")
[jovian] Detected Colab notebook... [jovian] Please enter your API key ( from https://jovian.ai/ ): API KEY:
 
himani007
Himani Gulati7 months ago
Jovian
Sign In