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?
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.
Errors cannot be handled, while Python exceptions can be handled at the run time. An error can be a syntax (parsing) error, while there can be many types of exceptions that could occur during the execution and are not unconditionally inoperable.
try: with open("example. txt") as my_file: for line in myfile: print(line) except: print("There was an error when reading the file.") An except block can hide the actual error: the problem here was not caused by file handling as such, but by the variable name which was misspelled.
Python ValueError is raised when a function receives an argument of the correct type but an inappropriate value. Also, the situation should not be described by a more precise exception such as IndexError.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With