LookupError Exception in Python

By Lenin Mishra

This is the part of the 9th day in the Python 30 series. Check out the series here.

The LookupError exception in Python forms the base class for all exceptions that are raised when an index or a key is not found for a sequence or dictionary respectively.

Exception
-> LookupError
--> IndexError
--> KeyError

This means, you can use LookupError exception class to handle both IndexError and KeyError exception classes.

Example 1 - Handling IndexError exception

Code/Output

# lists
x = [1, 2, 3, 4]
try:
    print(x[10])
except LookupError as e:
    print(f"{e}, {e.__class__}")

>>> list index out of range, <class 'IndexError'>

# strings
x = "Pylenin"
try:
    print(x[10])
except LookupError as e:
    print(f"{e}, {e.__class__}")

>>> string index out of range, <class 'IndexError'>    
    
# tuples
x = (1, 2, 3, 4)
try:
    print(x[10])
except LookupError as e:
    print(f"{e}, {e.__class__}")

>>> tuple index out of range, <class 'IndexError'>

As you can see, it is possible to catch IndexError exceptions using the LookupError exception class. By using e.__class__ method also helps you to identify the type of LookupError. In the above example, it is an IndexError.

Example 2 - Handling KeyError exception

Code

pylenin_info = {'name': 'Lenin Mishra',
                'age': 28,
                'language': 'Python'}
user_input = input('What do you want to learn about Pylenin==> ')

try:
    print(f'{user_input} is {pylenin_info[user_input]}')
except LookupError as e:
    print(f'{e}, {e.__class__}')

Output

What do you want to learn about Pylenin==> wife
'wife', <class 'KeyError'>

Check out other Python Built-in Exception classes in Python.

  1. Try, Except, Else and Finally in Python
  2. ZeroDivisionError Exception in Python
  3. OverflowError Exception in Python
  4. ArithmeticError Exception in Python
  5. KeyError Exception in Python
  6. IndexError Exception in Python
  7. StopIteration Exception in Python
  8. TypeError Exception in Python
  9. NameError Exception in Python
  10. FileNotFoundError Exception in Python
  11. Catch Multiple Exceptions in Python