How to catch IndexError Exception in Python?

PythonServer Side ProgrammingProgramming

An IndexError is raised when a sequence reference is out of range.

The given code is rewritten as follows to catch the exception and find its type

Example

import sys
try:
my_list = [3,7, 9, 4, 6]
print my_list[6]
except IndexError as e:
print e
print sys.exc_type

Output

C:/Users/TutorialsPoint1~.py
list index out of range
<type 'exceptions.IndexError'>

raja
Published on 06-Dec-2017 13:09:10
Advertisements