15.1. Exception About
Used when error occurs
You can catch exception and handles erroneous situation
If file does not exists
If no permissions to read file
If function argument is invalid type (ie.
int('one')
)If value is incorrect (ie. negative Kelvin temperature)
If network or database connection could not be established
15.1.1. AttributeError
Attribute reference or assignment fails
>>> data = ('a', 'b', 'c')
>>> data.append('x')
Traceback (most recent call last):
AttributeError: 'tuple' object has no attribute 'append'
15.1.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
15.1.3. IsADirectoryError
Trying to open directory instead of file
>>> open('/tmp')
Traceback (most recent call last):
IsADirectoryError: [Errno 21] Is a directory: '/tmp'
15.1.4. FileNotFoundError
File does not exists
>>> open('myfile.txt')
Traceback (most recent call last):
FileNotFoundError: [Errno 2] No such file or directory: 'myfile.txt'
15.1.5. KeyError
Dictionary key is not found
>>> data = {'a':1, 'b':2, 'c':3}
>>> data['x']
Traceback (most recent call last):
KeyError: 'x'
15.1.6. ModuleNotFoundError
Module could not be located
>>> import pprint
>>> import print
Traceback (most recent call last):
ModuleNotFoundError: No module named 'print'
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.
15.1.7. NameError
Local or global name is not found
>>> print(firstname)
Traceback (most recent call last):
NameError: name 'firstname' is not defined
15.1.8. SyntaxError
Parser encounters a syntax error
>>> if True
... print('a')
Traceback (most recent call last):
SyntaxError: expected ':'
15.1.9. IndentationError
Syntax errors related to incorrect indentation
>>> if True:
... print('a')
... print('b')
... print('c')
Traceback (most recent call last):
IndentationError: unexpected indent
15.1.10. TypeError
Operation or function is applied to an object of inappropriate type
>>> data = ['a', 'b', 'c']
>>> data[1]
'b'
>>> data = ['a', 'b', 'c']
>>> data[1.0]
Traceback (most recent call last):
TypeError: list indices must be integers or slices, not float
15.1.11. ValueError
Argument has an invalid value
>>> float('1')
1.0
>>> float('one')
Traceback (most recent call last):
ValueError: could not convert string to float: 'one'