[英]When should I raise LookupError in python?
Python's built-in exception documentation defines LookupError
as: Python的内置异常文档将
LookupError
定义为:
The base class for the exceptions that are raised when a key or index used on a mapping or sequence is invalid: IndexError, KeyError.
当映射或序列上使用的键或索引无效时引发的异常的基类:IndexError,KeyError。 This can be raised directly by codecs.lookup().
这可以通过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). 如果你是一个懒惰的人,你会使用LookupError同时捕获KeyError和IndexError(以免你说有一个字典填充了列表)。 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:
). 此外,可能还有其他异常是LookupError的变体(见下文),并且您也不希望捕获这些异常(同样的原因
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. 使用LookupError的另一种方法是,如果您需要自己的异常,因为此异常所代表的错误是由KeyError描述的错误,也不是IndexError,而是一种LookupError。 In this case your custom exception could inherit from LookupError.
在这种情况下,您的自定义异常可以从LookupError继承。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.