gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 10:03:33 25 4
gpt4 key购买 nike

我发现需要这样做:

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))

关于python - 捕获和重新抛出异常的替代方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42143096/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com