[英]I want to return KeyError not None
I want to return KeyError
but instead it returns None
. 我想返回KeyError
但是它返回None
。 I do not understand why. 我不理解为什么。
if index == self.length or self.slots[index]==None:
raise KeyError
You don't raise a KeyError
because you don't enter the if
-branch. 您不会引发 KeyError
因为您没有输入if
-branch。 And you don't enter the if
-branch because none of your conditions is true
. 而且您不会输入if
-branch,因为您的条件都不true
。
You probably need to adjust your condition if the test-case (that you haven't shown!) should really raise the KeyError
. 如果测试用例(未显示!)确实引发KeyError
,则可能需要调整条件。
To debug this issue you can insert some print
-statements: 要调试此问题,您可以插入一些print
语句:
print(index, self.length, index==self.length)
print(self.slots[index], self.slots[index]==None)
if index == self.length or self.slots[index]==None:
raise KeyError
or use a debugger of your choice. 或使用您选择的调试器。
However some comments: 但是一些评论:
>=
to the length (that includes ==
!). 通常,您要检查索引是否>=
==
长度(包括==
!)。 None
using is
. 您应该使用is
与None
进行is
。 None
and NotImplemented
are guaranteed singletons. None
和NotImplemented
是有保证的单例。 KeyError
, for example raise KeyError('index out of bounds or item is None! Try again.')
在KeyError
使用异常消息,例如, raise KeyError('index out of bounds or item is None! Try again.')
return
will return None
. 未命中显式return
的函数将返回None
。 That's probably why your code returned None
instead! 这可能就是为什么您的代码返回None
原因!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.