Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How to catch IndexError Exception in Python?

When I am running the following code, I am getting error

my_list = [3,7, 9, 4, 6]
print my_list[6]

How do I catch this exception and know its type?


1 Answer
codefoxx

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

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

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.