如果Python中出现异常重试

Ber*_*rer 2 python try-catch conditional-statements

我怎样才能去做这样的事情

  1. 尝试做某事。
  2. 如果有效,那就好,继续正常流程。
  3. 如果失败,运行一个函数并重试。
  4. 如果再次失败,则会抛出异常并停止代码。

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

Mak*_*oto 5

听起来您根本不想进行嵌套的 try-catch。作为控制流的异常是一种粗糙的反模式,在可以避免的地方就应该避免。

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

考虑到这一点,我们希望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
Run Code Online (Sandbox Code Playgroud)