2024-04-18 21:36:03 发布
网友
如果某个列表的大小不是某个值的倍数,我应该引发什么类型的错误?你知道吗
请考虑以下代码段:
def func(x: []): if ( len(x) % 2) != 0: raise WhatError("?") # ...
我考虑过TypeError、ValueError和IndexError,但我认为这些都不适合我的问题。 这类问题有没有错误类型,或者我应该咬紧牙关使用其中一个?你知道吗
TypeError
ValueError
IndexError
从ValueError的documentation开始:
exception ValueErrorRaised 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.
exception 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.
这对你来说似乎很合适。它也是Python库中用于无效参数的常用方法,例如在math模块中。还要记住,您可以在错误中提供更具体的原因,例如
math
raise ValueError("List must have even number of elements")
关于你的其他选择:TypeError似乎不合适,因为类型是正确的。如果长度不是偶数,那么IndexError可能会进一步下移,但是由于您没有将任何作为索引的内容传递给函数本身,因此我也不会使用该函数。你知道吗
列表的元素数是其值的一部分,因此在3个元素中,ValueError是最合适的。TypeError如果不是list/iterable,则是合适的,而IndexError通常在尝试访问x[i]元素时使用,并且列表的大小不对。你知道吗
x[i]
从
ValueError
的documentation开始:这对你来说似乎很合适。它也是Python库中用于无效参数的常用方法,例如在
math
模块中。还要记住,您可以在错误中提供更具体的原因,例如关于你的其他选择:
TypeError
似乎不合适,因为类型是正确的。如果长度不是偶数,那么IndexError
可能会进一步下移,但是由于您没有将任何作为索引的内容传递给函数本身,因此我也不会使用该函数。你知道吗列表的元素数是其值的一部分,因此在3个元素中,
ValueError
是最合适的。TypeError
如果不是list/iterable,则是合适的,而IndexError
通常在尝试访问x[i]
元素时使用,并且列表的大小不对。你知道吗相关问题 更多 >
编程相关推荐