写这个异常处理的正确方法是什么?



我只希望我的列表中有一个元素。如果列表为空,则抛出一个异常,如果列表有多个元素,则抛出另一个异常。

以下代码完成任务,但我不认为这是写以及它应该以任何标准。此外,如果满足列表大于1的条件,我希望它打印python错误"索引超出范围";和另一种情况一样。我该如何改进呢?

x = []
try:
if len(x) > 1:
raise Exception
else:
testVar = x[0]
except IndexError as e:
print(e)
print("list does not have any elements.")
except Exception as e:
print(e)
print("There are too many elements in the list.")

有更好的写法

def func(x):
if not x:
print("list does not have any elements.")
return None
if len(x) > 1:
print("There are too many elements in the list.")
return None
return x[0]

请注意,如果我们省略了前三行,那么当您引用x[0]时,Python将自动引发IndexError。

相关内容

最新更新