python - 有一个 "this should never happen"声明是好的做法吗

标签 python

在 python 中(以及一般的编码,真的)是一个不应该发生的错误的好习惯,还是只是代码困惑?

例如

if thing:
   num = 1
elif thing2:
   num = 2
else:
   num = 3

#Lots of other code goes here interacting with num, but not modifying it

if num == 1:
   option1()
elif num == 2:
   option2()
elif num == 3:
   option3()
else:
   #this should never happen
   print("Instead of being 1, 2, or 3, num was " + str(num))
   raise Exception("Error! num was an unexpected value!")

所以基本上,包括最后的 else(永远不应该发生)是好的做法,还是只是让代码变得困惑?

我的实际代码比这更复杂——具体来说,num 在主循环中赋值,然后传递给函数。也许它值得包括在内,因为该函数可能会从其他地方调用,并且 num 的值不正确?

最佳答案

处理默认条件通常被认为是好的做法,即使在当前代码中无法访问也是如此。这样做的原因是代码会随着时间的推移而增长和转移所有权,而目前看来无法实现的情况很可能在未来发生。在这种情况下,最好像您一样引发异常,而不是有未指定的行为。

关于python - 有一个 "this should never happen"声明是好的做法吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53788425/

相关文章:

Python 是否可以重新创建整个调用堆栈?

python - 删除单词开头的标点符号(特殊符号除外)

python - 如何处理启用 telegram bot 的错误?

Python改变B类中的类实例变量

python - 分而治之策略来确定列表中是否有超过 1/3 的相同元素

python - os.getlogin() 和 os.environ 获取用户名的区别

python构造函数基础问题

python - np.where() 没有返回 numpy python 中的预期索引

python - 无法在 Ubuntu Linux 16 上的 Python 2.7 中导入 pyttsx

python - 无法从网页解析特定值