简体   繁体   中英

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?

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. Eg:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM