问题描述
我发现需要这样做:
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))
这似乎有点愚蠢,因为我在捕获异常只是为了重新抛出异常,但是这次却获得了更多信息 。
是否有替代方法,还是这被视为标准做法?
1楼
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))
2楼
我建议的唯一调整是将这些与raise
的from
子句链接在一起。
在当前设置中,异常回溯指向您可能希望通知用户/开发人员错误从哪个确切行发出时的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
除此之外,我个人还没有看到其他任何替代方法,即使我不能说这是“标准的”,这也不是一件坏事,但您始终希望您的例外情况能提供更多信息。