LookupError Exception in Python

Handle Lookup error exceptions in Python using try-except block.

LookupError Exception in Python
Lookup Error in Python

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.

You can use LookupError exception class to handle both IndexError and KeyError exception classes.

- LookupError
 --> IndexError
 --> KeyError

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.

built-in-exception-classes - Pylenin
A programmer who aims to democratize education in the programming world and help his peers achieve the career of their dreams.