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 LookupError Exception in Python?

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

foo = [a, s, d, f, g]
print foo[5]

How do I catch this exception and know its type?


1 Answer
Manogna

LookupError Exception is the Base class for errors raised when something can’t be found. The base class for the exceptions that are raised when a key or index used on a mapping or sequence is invalid: IndexError, KeyError.

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:
foo = [a, s, d, f, g]
print foo[5]
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.