How to catch IndexError Exception in Python?


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'>

Updated on: 12-Feb-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements