Catch LookupError Exception in Python



LookupError in Python is the base class for errors that occur when a lookup using a key or index fails to find the expected value. This includes exceptions like IndexError and KeyError. If any lookup operation fails, a LookupError or one of its subclasses is raised.

In this article, you will learn how to catch LookupError exceptions in Python and handle them to prevent your program from crashing abruptly. LookupError is commonly raised when -

  • You access an invalid index in a list or a tuple.
  • You use a missing key in a dictionary.
  • You access an invalid index in a string.

Using try-except to Catch LookupError

You can use a try-except block to catch LookupError, which will also catch its subclasses like IndexError and KeyError.

Example

In this example, we access an index from the list that does not exist, which raises a LookupError -

try:
   data = [10, 20, 30]
   print(data[5])
except LookupError:
   print("LookupError caught: Invalid index in the list.")

We get the output as shown below -

LookupError caught: Invalid index in the list.

Handling Dictionary Key Errors

When we define an Item (key-value pair) in a dictionary with a key missing, and if we try to retrieve it (lookup), an exception is generated at the time of execution. The actual exception generated here is KeyError, but LookupError will still catch it -

Example

In the following example, we try to access a dictionary key that does not exist -

try:
   student = {"name": "Rohan", "age": 21}
   print(student["grade"])
except LookupError:
   print("LookupError caught: Key not found in dictionary.")

Following is the output obtained -

LookupError caught: Key not found in dictionary.

Printing the Exception Message

If we want to print the original exception message (of the exception raised), we need to capture the exception object using the "as" keyword and print it.

Example

Here, we print the error message for better debugging -

try:
   numbers = (1, 2, 3)
   print(numbers[10])
except LookupError as e:
   print("Caught LookupError:", e)

The error obtained is as shown below -

Caught LookupError: tuple index out of range

Catching Subclasses Specifically

If needed, you can also catch specific subclasses, like IndexError or KeyError to handle the exception precisely.

Example

In this example, only IndexError is caught, not the KeyError -

try:
   mylist = [1, 2, 3]
   print(mylist[7])
except IndexError:
   print("IndexError caught: List index out of range.")

We get the output as shown below -

IndexError caught: List index out of range.
Updated on: 2025-05-27T12:11:54+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements