[英]What exception to raise for python function arguments
I'm creating a function right now that takes in two lists. 我现在正在创建一个包含两个列表的函数。 I want these two lists to be of equal size.
我希望这两个列表大小相等。 I'm trying to figure out what kind of exception I should throw (or If I should throw an exception at all) if they aren't the same size.
我试图弄清楚如果它们的大小不一样,我应该抛出哪种异常(或者如果我应该抛出异常)。 I kind of want to say ValueError but this is a check that doesn't actually pertain to any single value.
我有点想说ValueError,但这是实际上不涉及任何单个值的检查。
For clarities sake, here's my function stub. 为了清楚起见,这是我的功能存根。
def create_form(field_types, field_discriptions):
pass
You can create your own subclass of exception called ArraysNotEqualSizeException. 您可以创建自己的异常子类,称为ArraysNotEqualSizeException。 Might be a bit overkill, but it gets the point across.
可能有点矫kill过正,但这很重要。
I would just use assert
and raise an AssertionError
: 我将只使用
assert
并引发AssertionError
:
assert len(field_types) == len(field_descriptions), "Helpful message"
Otherwise, ValueError
with a message seems like the best choice. 否则,带有消息的
ValueError
似乎是最佳选择。
throw an exception as the first thing in the function. 将异常作为函数中的第一件事。 A function-critical error should not do anything without making sure it can do what it wants or it could have bad effects
关键功能错误不应在不确保其能够完成所需操作的情况下采取任何措施,否则可能会产生不良影响
This isn't a giant error; 这不是一个大错误。 you should use an assert
你应该使用一个断言
Places to consider putting assertions:
考虑放置断言的地方:
checking parameter types, classes, or values checking data structure invariants checking "can't happen" situations (duplicates in a list, contradictory state variables.) after calling a function, to make sure that its return is reasonable - Python wiki
在调用函数后检查参数类型,类或值,检查数据结构不变性,以检查“不可能发生”的情况(列表中的重复项,矛盾的状态变量。),以确保其返回是合理的-Python Wiki
assert len(listone) == len(listtwo),
"the function cannot continue because\
the two arguments passed are of invalid length"
a ValueError
as suggested by Blender would be the right type if you want to use a generic exception, however that's usually reserved for larger issues and would be less helpful. 一个
ValueError
,如果你想使用一个通用的异常,但是,通常列于大型问题,并会少些有益的,通过搅拌机建议是正确的类型。
for quick reference: 快速参考:
"ValueError
“ ValueError
Raised when a built-in 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 docs
当内置操作或函数接收到具有正确类型但值不适当的参数,并且情况未由更精确的异常(如IndexError)描述时引发。”- Python docs
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.