Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

747
Views
When should I raise LookupError in python?

Python's built-in exception documentation defines LookupError as:

The base class for the exceptions that are raised when a key or index used on a mapping or sequence is invalid: IndexError, KeyError. This can be raised directly by codecs.lookup().

Should this base class be used only when catching try sections that access dictionaries using both indices and keys when one wants to shorthand catching both, or is there another case where you would use it?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

First of all dictionaries only use keys (see: How to index into a dictionary?).

If you are a lazy person you cold catch both KeyError and IndexError with the LookupError (lest say you have a dictionary filled with lists). Never the less i would prefer to catch them separately with two different exceptions. E.g.:

try:
    # do some stuff here
except KeyError:
    # key error handling
except IndexError:
    # index error handling

This way you can respond to these exceptions in different ways, as they were caused by different events. Furthermore there might be other exceptions that are a variation of a LookupError (see below) and you do not want to catch these exceptions as well (same reason one does not simply use except:).

Another way to use the LookupError could be if you are in need of your own exception, as your error that this exception represents is nether described by a KeyError, nor an IndexError, but is a type of LookupError. In this case your custom exception could inherit from LookupError.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!