gpt4 book ai didi

python - 如果在 Python 中出现异常重试

转载 作者:行者123 更新时间:2023-12-05 09:21:28 26 4
gpt4 key购买 nike

我怎么能去做这样的事情

  1. 尝试做点什么。
  2. 如果有效,很好,继续正常流程。
  3. 如果失败,运行函数并重试。
  4. 如果它再次失败抛出异常并停止代码。

我相信我必须使用try,但我还没有完全理解如何在这个特定示例中使用它。

最佳答案

听起来您根本不想进行嵌套的 try-catch。 Exceptions as control flow are a gnarly anti-pattern ,在可以避免的地方,您应该

在这种情况下,避免很容易。在您描述的方法中,您希望在对文件执行某些操作之前确保该文件存在。如果不是,您还有一种方法可以“更正”路径。如果两次尝试都失败了,那么你想摆脱困境。

考虑到这一点,我们希望使用 os.path.isfile为此。

from os.path import isfile

def something(filepath):
# Don't mutate the parameter if you can help it.
p = filepath
if not isfile(p):
p = correct_path(p)
if not isfile(p):
raise Error("Cannot find file {} after correction to {}, aborting.".format(filepath, p))
with open(p, 'r') as f:
# Rest of file operations here

关于python - 如果在 Python 中出现异常重试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32040317/

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