简体   繁体   English

我想返回KeyError不是None

[英]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: 但是一些评论:

  • Normally you want to check if the index is >= to the length (that includes == !). 通常,您要检查索引是否>= ==长度(包括== !)。
  • You should compare to None using is . 您应该使用isNone进行is None and NotImplemented are guaranteed singletons. NoneNotImplemented是有保证的单例。
  • Use an Exception message in 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.')
  • Functions that don't have hit an explicit return will return None . 未命中显式return的函数将返回None That's probably why your code returned None instead! 这可能就是为什么您的代码返回None原因!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM