7 Most Common In-Built Exceptions in Python!

As developers, encountering exceptions now and then is a part and parcel of our daily lives. They pop up in unexpected situations and are annoying to deal with.

In this article let us have a look at the 7 most common exceptions that will pop up from your Python code and see how to deal with them like professionals!

Let’s start with FileNotFoundError which is Ranked#7 in our list!

#7: FileNotFoundError

The FileNotFoundError is an error that occurs when you try to request a file or directory that does not exist on your device.

The usual causes of FileNotFoundError are:

  • File name incorrect
  • File extension incorrect or not included &
  • File is not in the expected location

No matter what your particular situation is, there is a step-by-step process you can follow to fix them, here it is!

Python FileNotFoundError: A Step By Step Troubleshooting Guide!

Next, let us look at NameError which is Ranked#6 in our list!

#6: NameError

The NameError in Python is an exception that is raised when the interpreter does not recognize a given name.

Have a look at the following piece of code:

print(a)

OUTPUT:

Traceback (most recent call last):
  File "/home/main.py", line 1, in <module>
    print(a)
NameError: name 'a' is not defined

Here, the interpreter didn’t know what variable a is since we did not define it, so it raises a NameError.

In the above case, the code itself is simple, but what if you have a complicated code dealing with 100 libraries and 1000 files?

We have devised a step-by-step process you can follow to fix any NameError! Here is our strategy!

Python NameError: A Step By Step Troubleshooting Guide!

Coming in at Number#5 on our list is…..AttributeError!

#5 AttributeError

An AttributeError is an exception that is triggered when you call a class’s attribute that does not exist. In other words, it is when an attribute reference fails

For instance:

class maths:
    def __init__(self, a ,b):
        self.a = a
        self.b = b
    def add(self):
        return self.a + self.b
    def subtract(self):
        return self.a - self.b
        
m1 = maths(2,5)

print(m1.a)
print(m1.add())

OUTPUT:

2
7

We defined two class variabes a and b, and two class methods add() and subtract(). We then create an object m1 and call this object’s attribute a (we refer to the attribute m1 of the object a) :

print(m1.a)

And then we call the add() function:

print(m1.add())

Both these calls worked perfectly as they are valid attributes and methods of the class. 

However, if we call a method that we didn’t define, let’s say multiply(), we would raise an AttributeError:

print(m1.multiply())

OUTPUT:

Traceback (most recent call last):
  File "/home/main.py", line 14, in <module>
    print(m1.multiply())
AttributeError: 'maths' object has no attribute 'multiply'

The last line of the error message clearly explains everything: the object of the class ‘maths’ does not have an attribute called ‘multiply’.

This is not the only situation that might lead to an AttributeError though, you can find many more interesting cases which are very tricky to find and fix. You can find those cases in the article linked below!

Python AttributeError: A Step By Step Troubleshooting Guide!

Next, coming in #4 of our list is ValueError!

#4: ValueError

The value error is an exception that is raised when an incorrect value is passed to a function. For instance, it might mean that the value you have passed is non-existent or it is invalid. ValueError is concerned with the value of the argument, not its data type.

Have a look at this example that raised a ValueError:

a = "5"
b = "five"

print(int(a))
print(int(b))

OUTPUT:

5
Traceback (most recent call last):
File "/home/main.py", line 5, in <module>
    print(int(b))
ValueError: invalid literal for int() with base 10: 'five’

The int() is a function that is used to convert a given string into an integer.

Whilst it successfully converts the string “5” into an integer, the same process fails for “five” as the function int( ) does not know how to deal with alphabets!

Both “5” and “five” are strings, but the 2nd one has an error in the value (presence of alphabets) and hence a ValueError was raised!

If it feels fuzzy fear not, we have an entire article dedicated to learning about the nitty-gritty of ValueError, which is linked below!

Python ValueError: A Step By Step Troubleshooting Guide!

Next, coming in number#3 on our list is:

#3: ModuleNotFoundError

The ModuleNotFoundError is an error that Python raises when it fails to locate and import a module. It typically pops up when there is an issue with your module’s name, location/directory, and surrounding environment

Here are 4 main reasons why this can happen:

  1. You haven’t installed the module,
  2. Misspelling the module name,
  3. Forgetting that names in Python are case-sensitive or
  4. Problem with your environment setup.

To determine what caused the issue in your case and how to fix that will need some strategic thinking, as with the other errors we got your back on this one too with the following article!

Python ModuleNotFoundError: A Step By Step Troubleshooting Guide!

Next, coming in number#2 on our list is…

#2: KeyError

A KeyError in Python is thrown when you try to access an item that does not exist in Python. For example:

fruits = {"a":"apple", "b":"orange"}

print(fruits["a"])
print(fruits["c"])

OUTPUT:

apple
Traceback (most recent call last):
  File "/home/main.py", line 4, in <module>
    print(fruit["c"])
KeyError: 'c'

In the above example, we tried to access the values associated with 2 keys. The first was key ‘a’ that returned its value without any issue.
When we called the second key “c”, we ran into a KeyError. This is because there is no key called “c” in the dictionary fruits

Python provides us with 2 convenient tools to avoid KeyError:

  1. get()
  2. setdefault()

To learn how to use these methods to fix KeyErrors head over to the following article!

KeyError: A Step By Step Troubleshooting Guide!

If you are thinking KeyErrors only occur with dictionaries, then you are in for a treat, as they occur with sets too!

KeyError In Sets And How To Avoid Them!

Alright, moving on to the top exception and our winner……….

#1: TypeError

The Type Error is raised when you attempt to operate using incompatible operands, here’s an example:

print(1+"a")

Here, we are attempting to add an integer with a string type. As the data types of these operands (‘1’ and ‘a’) are not compatible, a TypeError is raised:

OUTPUT:

Traceback (most recent call last):
  File "/home/main.py", line 1, in <module>
    print(1+"a")
TypeError: unsupported operand type(s) for +: 'int' and 'str

The above example might look simple enough, but the reason TypeError got the 1st place in our list is that TypeErrors are really tricky to debug and fix!

Some of the tricky causes of TypeError are

  1. Passing an incorrect type to a function e.g. passing a list to the built-in add() function.
  2. Calling a non-callable object e.g. calling an integer:
  3. Incorrect list index type e.g. using a string as a list index value instead of an integer.
  4. Iterating on a non-iterative value e.g. trying to iterate on an integer

Intrigued by the above list? Head over to the article below if you wish to master this concept and make your coding journey smoother!

TypeError: A Step By Step Troubleshooting Guide!

If you are a visual learner here is a YouTube video we made on the same topic as this article!

And with that, I will end this article!

Congratulations on making it to the end of the article, not many have the perseverance to do so!

I hope you enjoyed reading this article and found it useful!

Feel free to share it with your friends and colleagues!

If your thirst for knowledge has not been quenched yet, here are some related articles that might spark your interest!

Related Articles

Python: Details contained in an Exception

Python: “try-except-else-finally” Usage Explained!

Mutable and Immutable Data Types in python explain using examples

Photo of author
Editor
Balaji Gunasekaran
Balaji Gunasekaran is a Senior Software Engineer with a Master of Science degree in Mechatronics and a bachelor’s degree in Electrical and Electronics Engineering. He loves to write about tech and has written more than 300 articles. He has also published the book “Cracking the Embedded Software Engineering Interview”. You can follow him on LinkedIn