Python – Error Types

Created with Sketch.

Python – Error Types

The most common reason of an error in a Python program is when a certain statement is not in accordance with the prescribed usage.
Such an error is called a syntax error. The Python interpreter immediately reports it, usually along with the reason.

>>> print “hello”
SyntaxError: Missing parentheses in call to ‘print’. Did you mean print(“hello”)?

In Python 3.x, print is a built-in function and requires parentheses. The statement above violates this usage and hence syntax error is displayed.

Many times though, a program results in an error after it is run even if it doesn’t have any syntax error. Such an error is a runtime error, called an exception.
A number of built-in exceptions are defined in the Python library.
Let’s see some common error types.

IndexError is thrown when trying to access an item at an invalid index.

>>> L1=[1,2,3]
>>> L1[3]
Traceback (most recent call last):
File “<pyshell#18>”, line 1, in <module>

IndexError: list index out of range

ModuleNotFoundError is thrown when a module could not be found.

>>> import notamodule
Traceback (most recent call last):
File “<pyshell#10>”, line 1, in <module>

import notamodule
ModuleNotFoundError: No module named ‘notamodule’

KeyError is thrown when a key is not found.

>>> D1={‘1’:”aa”, ‘2’:”bb”, ‘3’:”cc”}
>>> D1[‘4’]
Traceback (most recent call last):
File “<pyshell#15>”, line 1, in <module>

KeyError: ‘4’

ImportError is thrown when a specified function can not be found.

>>> from math import cube
Traceback (most recent call last):
File “<pyshell#16>”, line 1, in <module>

from math import cube
ImportError: cannot import name ‘cube’

StopIteration is thrown when the next() function goes beyond the iterator items.

>>> it=iter([1,2,3])
>>> next(it)
>>> next(it)
>>> next(it)
>>> next(it)
Traceback (most recent call last):
File “<pyshell#23>”, line 1, in <module>


TypeError is thrown when an operation or function is applied to an object of an inappropriate type.

>>> ‘2’+2
Traceback (most recent call last):
File “<pyshell#23>”, line 1, in <module>

TypeError: must be str, not int

ValueError is thrown when a function’s argument is of an inappropriate type.

>>> int(‘xyz’)
Traceback (most recent call last):
File “<pyshell#14>”, line 1, in <module>

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

NameError is thrown when an object could not be found.

>>> age
Traceback (most recent call last):
File “<pyshell#6>”, line 1, in <module>

NameError: name ‘age’ is not defined

ZeroDivisionError is thrown when the second operator in the division is zero.

>>> x=100/0
Traceback (most recent call last):
File “<pyshell#8>”, line 1, in <module>

ZeroDivisionError: division by zero

KeyboardInterrupt is thrown when the user hits the interrupt key (normally Control-C) during the execution of the program.

>>> name=input(‘enter your name’)
enter your name^c
Traceback (most recent call last):
File “<pyshell#9>”, line 1, in <module>

name=input(‘enter your name’)

The following table lists important built-in exceptions in Python.

AssertionErrorRaised when the assert statement fails.
AttributeErrorRaised on the attribute assignment or reference fails.
EOFErrorRaised when the input() function hits the end-of-file condition.
FloatingPointErrorRaised when a floating point operation fails.
GeneratorExitRaised when a generator’s close() method is called.
ImportErrorRaised when the imported module is not found.
IndexErrorRaised when the index of a sequence is out of range.
KeyErrorRaised when a key is not found in a dictionary.
KeyboardInterruptRaised when the user hits the interrupt key (Ctrl+c or delete).
MemoryErrorRaised when an operation runs out of memory.
NameErrorRaised when a variable is not found in the local or global scope.
NotImplementedErrorRaised by abstract methods.
OSErrorRaised when a system operation causes a system-related error.
OverflowErrorRaised when the result of an arithmetic operation is too large to be represented.
ReferenceErrorRaised when a weak reference proxy is used to access a garbage collected referent.
RuntimeErrorRaised when an error does not fall under any other category.
StopIterationRaised by the next() function to indicate that there is no further item to be returned by the iterator.
SyntaxErrorRaised by the parser when a syntax error is encountered.
IndentationErrorRaised when there is an incorrect indentation.
TabErrorRaised when the indentation consists of inconsistent tabs and spaces.
SystemErrorRaised when the interpreter detects internal error.
SystemExitRaised by the sys.exit() function.
TypeErrorRaised when a function or operation is applied to an object of an incorrect type.
UnboundLocalErrorRaised when a reference is made to a local variable in a function or method, but no value has been bound to that variable.
UnicodeErrorRaised when a Unicode-related encoding or decoding error occurs.
UnicodeEncodeErrorRaised when a Unicode-related error occurs during encoding.
UnicodeDecodeErrorRaised when a Unicode-related error occurs during decoding.
UnicodeTranslateErrorRaised when a Unicode-related error occurs during translation.
ValueErrorRaised when a function gets an argument of correct type but improper value.
ZeroDivisionErrorRaised when the second operand of a division or module operation is zero.

Visit Python Docs for more information.

Learn how to handle exceptions in the next chapter.

Leave a Reply

Your email address will not be published. Required fields are marked *