【问题标题】:What is the proper way to write this exception handling?编写此异常处理的正确方法是什么?
【发布时间】:2021-09-29 00:41:46
【问题描述】:

我只希望我的列表中包含一个元素。如果列表为空,则应该引发一个异常,如果列表包含多个元素,则应该引发不同的异常。

以下代码完成了这项任务,但我认为它的编写并不符合任何标准。此外,如果满足列表大于一个的条件,我希望它像在其他条件下一样打印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.")

【问题讨论】:

  • 引发异常只是为了捕获它是没有意义的。
  • "index out of range" 在这里不是正确的错误,因为它没有描述条件。 ValueError 可能会更好。
  • 异常适用于您的函数不知道如何处理的异常情况,一般来说,应该谨慎使用。它们绝对不应该用于本地控制流。
  • 感谢您的所有反馈!

标签: python


【解决方案1】:

这是一个更好的写法。

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。

【讨论】:

  • 谢谢!我和这个一起去了。
猜你喜欢
  • 2013-08-31
  • 1970-01-01
  • 2012-02-24
  • 2012-03-29
  • 2010-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多