当前位置: 代码迷 >> python >> 捕获和重新抛出异常的替代方法
  详细解决方案

捕获和重新抛出异常的替代方法

热度:35   发布时间:2023-06-13 14:19:20.0

我发现需要这样做:

try:
    prop_file = next(file for file in os.listdir(data_folder) if 'property' in file)
except StopIteration:
    raise StopIteration('The property file could not be found in the specified folder ({})!'.format(data_folder))

这似乎有点愚蠢,因为我在捕获异常只是为了重新抛出异常,但是这次却获得了更多信息

是否有替代方法,还是这被视为标准做法?

StopIteration看起来不正确。

在这种情况下,您可以使next返回None

prop_file = next((file for file in os.listdir(data_folder)
                  if 'property' in file), None)
if not prop_file:
    message = 'The property file could not be found in the specified folder ({})!'
    raise AppropriateException(message.format(data_folder))

我建议的唯一调整是将这些与raisefrom子句链接在一起。 在当前设置中,异常回溯指向您可能希望通知用户/开发人员错误从哪个确切行发出时的raise语句(请考虑try主体包含许多语句的情况)。

您可以添加小调整:

try:
    prop_file = next(file for file in os.listdir(data_folder) if 'property' in file)
except StopIteration as e:
    msg = 'The property file could not be found in the specified folder ({})!'
    raise StopIteration(msg.format(data_folder)) from e

除此之外,我个人还没有看到其他任何替代方法,即使我不能说这是“标准的”,这也不是一件坏事,但您始终希望您的例外情况能提供更多信息。

  相关解决方案