gpt4 book ai didi

python - 在这种情况下如何防止 "too broad exception"?

转载 作者:IT老高 更新时间:2023-10-28 20:47:17 25 4
gpt4 key购买 nike

我有一个可能失败的函数列表,如果其中一个失败,我不希望脚本停止,而是继续执行下一个函数。

我正在用这样的东西执行它:

list_of_functions = [f_a, f_b, f_c]
for current_function in list_of_functions:
try:
current_function()
except Exception:
print(traceback.format_exc())

工作正常,但不符合 PEP8:

When catching exceptions, mention specific exceptions wheneverpossible instead of using a bare except: clause.

For example, use:

try:
import platform_specific_module
except ImportError:
platform_specific_module = None

A bare except: clause will catch SystemExit and KeyboardInterruptexceptions, making it harder to interrupt a program with Control-C,and can disguise other problems. If you want to catch all exceptionsthat signal program errors, use except Exception: (bare except isequivalent to except BaseException: ).

A good rule of thumb is to limit use of bare 'except' clauses to twocases:

If the exception handler will be printing out or logging the traceback; at least the user will be aware that an error has occurred.

If the code needs to do some cleanup work, but then lets the exception propagate upwards with raise . try...finally can be a betterway to handle this case.

我怎样才能做到这一点?

最佳答案

您引用的 PEP8 指南建议在您记录错误的情况下使用裸异常是可以的。我认为您应该涵盖尽可能多的异常/知道如何处理,然后记录其余的并pass,例如

import logging

list_of_functions = [f_a,f_b,f_c]
for current_function in list_of_functions:
try:
current_function()
except KnownException:
raise
except Exception as e:
logging.exception(e)

关于python - 在这种情况下如何防止 "too broad exception"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30442236/

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