7.2. Exception Commonly Raised

7.2.1. AttributeError

Attribute reference or assignment fails:

>>> name = 'Jan'
>>> name.append('Twardowski')
Traceback (most recent call last):
AttributeError: 'str' object has no attribute 'append'

7.2.2. IndexError

Sequence subscript is out of range:

>>> DATA = ['a', 'b', 'c']
>>> DATA[100]
Traceback (most recent call last):
IndexError: list index out of range

7.2.3. IsADirectoryError

Trying to open directory instead of file:

>>> open('/tmp')
Traceback (most recent call last):
IsADirectoryError: [Errno 21] Is a directory: '/tmp'

7.2.4. FileNotFoundError

File does not exists:

>>> open('notexisting.txt')
Traceback (most recent call last):
FileNotFoundError: [Errno 2] No such file or directory: 'notexisting.txt'

7.2.5. KeyError

Dictionary key is not found:

>>> DATA = {'a': 1, 'b': 2}
>>> DATA['x']
Traceback (most recent call last):
KeyError: 'x'

7.2.6. ModuleNotFoundError

Module could not be located:

>>> import math
>>> import match
Traceback (most recent call last):
ModuleNotFoundError: No module named 'match'

Note, that this exception is also raised when you don't have this module installed. Such as while importing pandas or numpy without installing it first.

7.2.7. NameError

Local or global name is not found:

>>> print(firstname)
Traceback (most recent call last):
NameError: name 'firstname' is not defined

7.2.8. SyntaxError

Parser encounters a syntax error:

>>> if True
...     print('Yes')
Traceback (most recent call last):
SyntaxError: invalid syntax

7.2.9. IndentationError

Syntax errors related to incorrect indentation:

>>> if True:
...     print('Hello!')
...      print('My name...')
...     print('José Jiménez')
Traceback (most recent call last):
IndentationError: unexpected indent

7.2.10. TypeError

Operation or function is applied to an object of inappropriate type:

>>> 42 + 'a'
Traceback (most recent call last):
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> 'a' + 42
Traceback (most recent call last):
TypeError: can only concatenate str (not "int") to str
>>> a = ['a', 'b', 'c']
>>> a[1.5]
Traceback (most recent call last):
TypeError: list indices must be integers or slices, not float
>>> a, b = 1
Traceback (most recent call last):
TypeError: cannot unpack non-iterable int object

7.2.11. ValueError

Argument has an invalid value:

>>> a, b, c = 1, 2
Traceback (most recent call last):
ValueError: not enough values to unpack (expected 3, got 2)
>>> a, b = 1, 2, 3
Traceback (most recent call last):
ValueError: too many values to unpack (expected 2)
>>> float('one')
Traceback (most recent call last):
ValueError: could not convert string to float: 'one'
>>> int('one')
Traceback (most recent call last):
ValueError: invalid literal for int() with base 10: 'one'