【问题标题】:Execute when error occurs python发生错误时执行python
【发布时间】:2025-06-16 08:45:02
【问题描述】:

我想我不是第一个问这个问题的人,但我还没有找到我可以使用/理解的解决方案。而且问题可能并不像我最初预期的那么简单。

我认为可以归结为两个一般性问题:

1) 有没有办法避免 Python 在发生错误时停止并直接跳到脚本中的下一行代码?

2) 如果发生错误,有没有办法让 Python 执行一行代码?就像,如果出错那么......

我的具体问题: 我有一个非常大的程序,其中包含很多功能和其他东西,例如通过使用“尝试”来单独调整(如果我理解正确的话)

我的程序作为一个大循环运行,它收集信息并继续运行。这意味着对我来说并不重要,只要我的程序继续运行,它就会多次失败。我可以轻松处理某些信息有错误,并且希望我的程序记下它并继续。

有解决办法吗?

【问题讨论】:

标签: python error-handling


【解决方案1】:

正如您正确指出的那样,Python 中的 try/catch 块是迄今为止您最好的盟友:

for i in range(N):
    try: do_foo()  ; except: do_other_foo()
    try: do_bar()  ; except: do_other_bar()

或者,如果您不需要异常,您也可以使用:

from contextlib import suppress

for i in range(N):
    with suppress(Exception):
        do_foo()
    with suppress(Exception):
        do_bar()

【讨论】:

    【解决方案2】:

    您唯一的可能是依赖try/except 子句。请记住,try/except 也可以使用finallyelse(参见documentation

    try:
        print("problematic code - error NOT raised")
    except:
        print("code that gets executed only if an error occurs")
    else:
        print("code that gets executed only if an error does not occur")
    finally:
        print("code that gets ALWAYS executed")
    # OUTPUT:
    # problematic code - error NOT raised
    # code that gets executed only if an error does not occur
    # code that gets ALWAYS executed
    

    或者,当出现错误时:

    try:
        print("problematic code - error raised!")
        raise "Terrible, terrible error"
    except:
        print("code that gets executed only if an error occurs")
    else:
        print("code that gets executed only if an error does not occur")
    finally:
        print("code that gets ALWAYS executed")
    # OUTPUT:
    # problematic code - error raised!
    # code that gets executed only if an error occurs
    # code that gets ALWAYS executed
    

    顺便说一句,我强烈要求指出,无视一切让我颤抖:
    您确实应该(至少,或多或少)确定可以引发哪些异常,捕获它们(except ArithmeticError: ...,检查built-in exceptions)并单独处理它们。您尝试做的事情可能会滚雪球成无穷无尽的问题链,而忽略它们可能会产生更多问题!

    我认为this question 有助于理解什么是强大的软件,同时在this one 你可以看到 SO 社区认为应该如何处理 python 异常

    【讨论】:

    • else 子句适用于在 try 中未引发任何错误的代码,来自 python 文档:“try ... except 语句有一个可选的 else 子句,如果存在,则必须遵循所有 except 子句. 如果 try 子句没有引发异常,则它对于必须执行的代码很有用。” docs.python.org/3/tutorial/errors.html
    • @MatthieuDsprz 感谢您指出复制粘贴错误;尽管有输出和尝试代码的可能性,但对于新程序员来说,这绝对是令人困惑的。修好了!
    最近更新 更多