Lessons on Python Error and Python Exception

1. Python Error and Python Exception

Life is going on great. You’re having a good time with Python when your code suddenly blows up when you finally run it. What could have possibly caused this? The code seemed all okay. To deal with such situations, we bring this tutorial to you which covers Python errors and Python exception with Python Exception Example. It will cover all possible python error and python exception to help you in running your python code smoothly as there are many reasons why to learn Python.

Python Error and Python Exception

Python Error and Python Exception

2. Syntax Errors in Python

In your code, when you mess up the rules of Python Syntax, your code doesn’t run. The following code causes a syntax error.

>>> if 2>1 print("2")

SyntaxError: invalid syntax

This code doesn’t run because it misses a colon after the condition 2>1.

A syntax error also called a parsing error, displays ‘Syntax Error: invalid syntax’.

3. Introduction to Python Exception

It may be convenient to recognize the problems in your python code before you put it to real use. But that does not always happen. Sometimes, problems show up when you run the code; sometimes, midway of that.

A Python exception is an error that’s detected during execution. It may be fatal for the program, but not necessarily so. Let’s take the most common example.

>>> a,b=1,0
>>> print(a/b)
Traceback (most recent call last):
File "<pyshell#208>", line 1, in <module>

ZeroDivisionError: division by zero

Throughout our python tutorials so far, you’ve noticed words like TypeError, NameError, and so. It’s time to find out what that is. Also learn Exception Handling in Python for Python Programming.

4. Python Error and Python Exception Message

When Python error and exceptions occurs, it prints a four-line message on the screen, if not handled.

The first line declares that this is a traceback. This means that the interpreter traces the exception back to its source.

The second tells us the line number for the code that caused the Python exception. In our case, it is line 1. #208 means this is the 208th statement we’re running in the interpreter since we opened it.

The third line tells us which line (the statement that) caused the exception.

Finally, the fourth line tells us the type of exception that occurred. This is accompanied by a short description to what happened.

5. In-built Python Exception

Now that we know what an exception is, we will talk of a list of python exception that are in-built in Python. As you read the list, try to recall if you ever encountered any of these Python exception. Tell us in the comments.

a. AssertionError in python

This exception raises when an assert statement fails. This is also called Python raise expression. A successful assert statement looks like this:

>>> assert(1==1)

But when we write the following code, we get an AssertionError:

>>> assert(1==2)
Traceback (most recent call last):
File "<pyshell#213>", line 1, in <module>


We’ll take the assert statement in detail in a future lesson.

b. AttributeError in python

This one occurs when an attribute assignment or reference fails. As an example, let’s take class ‘fruit’.

>>> class fruit:
>>> fruit.size
Traceback (most recent call last):
File "<pyshell#223>", line 1, in <module>

AttributeError: type object ‘fruit’ has no attribute ‘size’

Here, the attribute size does not exist. Hence, it raises an AttributeError.

c. EOFError in Python

This exception raises when the input() function reaches the end-of-file condition.

d. FloatingPointError in Python

When a floating point operation fails, this exception occurs.

e. GeneratorExit in python

This raises when a generator’s close() method is called.

f. ImportError in Python

When the imported module isn’t found, an ImportError occurs.

>>> from math import ppi
Traceback (most recent call last):
File "<pyshell#234>", line 1, in <module>
from math import ppi

ImportError: cannot import name ‘ppi’

g. IndexErrorin Python

When you access an index, on a sequence, that is out of range, you get an IndexError.

>>> list=[1,2,3]
>>> list[3]
Traceback (most recent call last):
File "<pyshell#236>", line 1, in <module>

IndexError: list index out of range

h. KeyError in Python

This raises when a key isn’t found in a dictionary.

>>> dict1={1:1,2:2}
>>> dict1[3]
Traceback (most recent call last):
File "<pyshell#239>", line 1, in <module>

KeyError: 3

i. KeyboardInterrupt in Python

This one occurs when the user hits the interrupt key (Ctrl + C).

>>> while True: print("Hello")
Traceback (most recent call last):
File "<pyshell#244>", line 1, in <module>
while True: print("Hello")


j. MemoryError in Python

This raises when an operation runs out of memory.

k. ModuleNotFoundError in Python

When you import a module that does not exist, you will get the ModuleNotFoundError.

>>> import maths
Traceback (most recent call last):
File "<pyshell#233>", line 1, in <module>
import maths

ModuleNotFoundError: No module named ‘maths’

l. NameError in Python

A NameError occurs when a name isn’t found in a scope.

>>> eggs
Traceback (most recent call last):
File "<pyshell#245>", line 1, in <module>

NameError: name ‘eggs’ is not defined

m. NotImplementedError in Python

An abstract method raises a NotImplementedError.

n. OSError in Python

Now this one is raised when a system operation causes a system-related error.

o. OverflowError in Python

This raises when the result of an arithmetic operation is too large to be represented.

p. ReferenceError in Python

This is raised when a weak reference proxy is used to access a garbage collected referent.

q. RuntimeError in Python

When an error does not fall under any specific category, we call it a RuntimeError.

r. StopIteration in Python

The next() function raises StopIteration to indicate that no further item is to be returned by the iterator.

>>> def countdown():
yield n
>>> c=countdown()
>>> next(c)
>>> next(c)
>>> next(c)
>>> next(c)
>>> next(c)
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>


s. IndentationError in Python

An IndentationError raises on incorrect indentation.

t. TabError in Python

When the indentation is inconsistent in tabs and spaces, there’s a TabError.

u. SystemError in Python

When the interpreter detects an internal error, it’s a SystemError.

v. SystemExit in Python

The sys.exit() function raises this one.

w. TypeError in Python

When you apply a function or an operation to an object of incorrect type, you get a TypeError.

>>> '10'+10
Traceback (most recent call last):
File "<pyshell#38>", line 1, in <module>

TypeError: must be str, not int

x. UnboundLocalError in Python

You get an UnboundLocalError when you try to access a local variable without first assigning a value to it.

>>> def sayhi():
>>> sayhi()
Traceback (most recent call last):
File "<pyshell#53>", line 1, in <module>
File "<pyshell#52>", line 2, in sayhi

UnboundLocalError: local variable ‘m’ referenced before assignment

y. UnicodeError in Python

When a Unicode-related encoding/decoding error occurs, you get the UnicodeError exception.

z. UnicodeEncodeError in Python

This is a Unicode error during encoding.

Learn: Python Inheritance, Method Overloading & Method Overriding

aa. UnicodeDecodeError in Python

The Unicode error during decoding is termed UnicodeDecodeError.

ab. UnicodeTranslateError in Python

A UnicodeTranslateError occurs during translating.

ac. ValueError in Python

You get a ValueError when you send in an argument of the correct type, but an improper value.

>>> int(input())
Traceback (most recent call last):
File "<pyshell#55>", line 1, in <module>

ValueError: invalid literal for int() with base 10: ‘3.5’

ad. ZeroDivisionError in Python

Finally, a ZeroDivisionError is one we’ve seen in section 3. When the denominator of a division is 0, this exception is raised. This doesn’t necessarily violate syntax.

>>> print(1/0)
Traceback (most recent call last):
File "<pyshell#56>", line 1, in <module>

ZeroDivisionError: division by zero

This is all about the Python Error and Python Exception.

6. Conclusion

In this module, we learned about Python Error and Python Exception, and looked at some in-built exceptions in python. These are unexpected situations at runtime. In our next module, we will learn how to handle them. Stay tuned.