[英]What error should I raise when a list size is not a multiple of some value?
What type of error should i raise if the the size of some list is not a multiple of some value? 如果某些列表的大小不是某个值的倍数,我应该引发哪种类型的错误?
Consider the following code snippet: 考虑以下代码片段:
def func(x: []):
if ( len(x) % 2) != 0:
raise WhatError("?")
# ...
I have considered TypeError
, ValueError
and IndexError
but I don't think any one of these fit my problem. 我已经考虑了
TypeError
, ValueError
和IndexError
但是我认为这些都不适合我的问题。 Are there an errortype for this type of problem or should I just bite the bullet and use one of these? 是否存在此类问题的错误类型,还是我应该硬着头皮使用其中一种?
From the documentation of ValueError
: 从
ValueError
的文档中:
exception
ValueError
异常
ValueError
Raised when an operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.
当操作或函数接收到类型正确但值不合适的参数时引发,并且这种情况没有通过更精确的异常(如IndexError)描述。
This seems appropriate in your case. 这似乎适合您的情况。 It's also what's commonly used in Python libraries for invalid arguments, eg in the
math
module. 这也是Python库中通常用于无效参数的内容,例如在
math
模块中。 Also remember that you can provide a more specific cause within the error, eg 还要记住,您可以在错误中提供更具体的原因,例如
raise ValueError("List must have even number of elements")
About your other alternatives: A TypeError
seems inappropriate, as the type is correct. 关于其他替代方案:
TypeError
似乎不合适,因为类型正确。 An IndexError
might have been raised further down the line if the length is not even, but as you do not pass anything that works as an index to the function itself, I would not use that one either. 如果长度不是偶数,可能会在行的最下方引发
IndexError
,但是由于您没有将任何可用作索引的内容传递给函数本身,因此我也不会使用该索引。
The number of elements of a list is part of its value , so, among the 3, ValueError
is the most appropriate. 列表中元素的数量是其值的一部分 ,因此,在3个值中,
ValueError
最合适。 TypeError
would be appropriate if it was not a list/iterable, while IndexError
as normally used when trying to access the x[i]
element and the list has the wrong size for that. 如果不是列表/可迭代类型,则
TypeError
将是适当的,而尝试访问x[i]
元素且列表具有错误的大小时,通常使用IndexError
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.