In this Tutorial -:


Pre–requisite: Exception Handling in Python
Exception in Python is considered as the runtime error that can be handled by a developer using various techniques of exception handling in Python.
Exceptions can be suppressed or handled using try, except, and finally block in Python. This mechanism of handling runtime errors is termed as Exception Handling in Python.
This tutorial is all about types of Exceptions in Python.
Types of Exceptions in Python
1. Exception in Python
This class covers all type of exception. All exceptions are the subclasses of this class.
Use of Exception class is helpful in all those situations where you are not sure which type of exception you should handle in your program.
Example code
def find_divisor(n1, n2):
try:
res = n1/n2
print('Result is : ', res)
except Exception as e:
print('Some Exception encountered.')
print('Details are: ', e)
# calling the method
find_divisor(20, 0)
O/P
Some Exception encountered.
Details are: division by zero
In the above code, instead of handling the specific exception, we have used common Exception class that will allow us to handle any exception that may occur in the program.
2. ArithmeticError Exception in Python
Use of ArithmeticError exception class is helpful in all those situations where you are sure that your program may throw an arithmetic error.
Example code
def find_divisor(n1, n2):
try:
res = n1/n2
print('Result is : ', res)
except ArithmeticError as a:
print('Arithmetic Exception encountered.')
print('Details are: ', a)
# calling the method
find_divisor(20, 0)
O/P
Arithmetic Exception encountered.
Details are: division by zero
In the above code, we have used ArithmeticError class that will allow us to handle any arithmetic error in the code.
3. Assertion Error Exception in Python
Use of AssertionError exception class is helpful in handling all the errors raised by assert statement. We recommend you to follow-up our tutorial on assert statement in python http://codeofgeeks.com/assert-statement-in-python-with-example/ for more information.
Example code
n = 7
assert n%2==0, "Odd Integers are not allowed !"
print("Square of {0} is {1}".format(n, n*n))
O/P
Traceback (most recent call last):
File “”, line 2, in
AssertionError: Odd Integers are not allowed !
Above code will not execute as it has the assertion error.
We can handle this using AssertionError class.
try:
n = 7
assert n%2==0, "Odd Integers are not allowed !"
print("Square of {0} is {1}".format(n, n*n))
except AssertionError as a:
print('Assertion Exception encountered.')
print('Details are: ', a)
O/P
Assertion Exception encountered.
Details are: Odd Integers are not allowed !
In the above code, we have used AssertionError class that will allow us to handle the error raised by assert statement in python.
4. Type Error Exception in Python
Use of TypeError exception class is helpful in handling all the errors that are raised when an operation is applied to an object of inappropriate datatype.
Example code
# program to increment a value
def increment(n):
try:
print('Incremented value: ', n+1)
except TypeError as t:
print('Type Error Exception encountered.')
print('Details are: ', t)
n = 'I am a string'
increment(n)
O/P
Type Error Exception encountered.
Details are: can only concatenate str (not “int”) to str
In the above code, we have used TypeError class that will allow us to handle the error raised when an operation of datatype is performed on other.
5. Value Error Exception in Python
Use of ValueError exception class is helpful in handling all the errors that are raised when an operation or function receives an argument with right datatype but wrong value.
Like, finding square root of negative number will give ValueError. Let’s handle this,
Example code
# program to find square root
import math
def square_root(n):
try:
print('Result: ', math.sqrt(n))
except ValueError as v:
print('Value Error Exception encountered.')
print('Details are: ', v)
n = -4
square_root(n)
O/P
Value Error Exception encountered.
Details are: math domain error
In the above code, we have used ValueError class that will allow us to handle the error raised when we passed negative value to find the square root of.
6. Key Error Exception in Python
Use of KeyError exception class is helpful in handling all the errors that are raised when a given mapping key is not found in the set of existing keys.
Like, finding a key in a dictionary that does not even exists, will result in KeyError.
Let’s handle this,
Example code
# program to find non-existing key
def find_key():
try:
d = {1: 'one', 2: 'two', 3: 'three'}
print(d[4]) # printing value of key 4 which is not present
except KeyError as k:
print('Key Error Exception encountered.')
print('Details are: ', k)
find_key()
O/P
Key Error Exception encountered.
Details are: 4
In the above code, we have used KeyError class that will allow us to handle the error raised when we tried to access the key which is not present.
7. Name Error Exception in Python
Use of NameError exception class is helpful in handling all the errors that are raised when an identifier (variable or method) is not found locally or globally.
Like, printing a value of a variable which is not declared.
Let’s handle this,
Example code
try:
a = 10
print(b)
except NameError as n:
print('Name Error Exception encountered.')
print('Details are: ', n)
O/P
Name Error Exception encountered.
Details are: name ‘b’ is not defined
In the above code, we have used NameError class that will allow us to handle the error raised when we tried to print a variable which is not declared.
8. Index Error Exception in Python
Use of IndexError exception class is helpful in handling all the errors that are raised when a given index is out of range.
Like, accessing a sixth element in a list of 5 element.
Let’s handle this,
Example code
try:
l = [10, 20, 30, 40, 50]
print(l[5]) # 0-based indexing
except IndexError as i:
print('Index Error Exception encountered.')
print('Details are: ', i)
O/P
Index Error Exception encountered.
Details are: list index out of range
In the above code, we have used IndexError class that will allow us to handle the error raised when we tried to access the 6th element of the list.
So, above are the most common types of exceptions in python while there are lot more these are most talked about.
NEXT TUTORIAL >> User Defined Exceptions in Python
