Built-in Python Exceptions with
Examples
ZeroDivisionError
Raised when you divide a number by zero.
Example:
result = 10 / 0
TypeError
Raised when an operation is applied to an object of inappropriate type.
Example:
result = '2' + 3
ValueError
Raised when a function receives a correct type but inappropriate value.
Example:
num = int('abc')
IndexError
Raised when accessing an index out of range in a list or string.
Example:
lst = [1, 2, 3]
print(lst[5])
KeyError
Raised when a dictionary key is not found.
Example:
d = {'a': 1}
print(d['b'])
NameError
Raised when a variable is not defined.
Example:
print(xyz)
AttributeError
Raised when an invalid attribute is accessed on an object.
Example:
x = 10
x.append(5)
ImportError
Raised when an import statement fails.
Example:
import maths
IndentationError
Raised when indentation is incorrect. (Cannot be caught by try-except)
Example:
# def func():
# print('Hello')
FileNotFoundError
Raised when a file or directory is requested but doesn't exist.
Example:
f = open('nofile.txt')
MemoryError
Raised when an operation runs out of memory.
Example:
a = [1] * (10 ** 100)
OverflowError
Raised when a numerical calculation exceeds limits of the data type.
Example:
import math
math.exp(1000)
StopIteration
Raised to signal the end of an iterator.
Example:
it = iter([1, 2])
next(it)
next(it)
next(it)
RuntimeError
Raised when an error is detected that doesn't fall in any category.
Example:
raise RuntimeError('Generic runtime error')