如何防止“过于广泛的例外”?在这种情况下?
我列出了可能会失败的功能,如果失败,我不希望脚本停止运行,而是继续下一个功能。
I got a list of functions that may fail, and if one fail, I don't want the script to stop, but to continue with next function.
我用这样的东西执行它:
I am executing it with something like this :
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:
It's working fine, but it is not PEP8 compliant:
在捕获异常时,请提及可能的特定例外,只要
可以使用而不使用裸的else:子句即可。
When catching exceptions, mention specific exceptions whenever possible instead of using a bare except: clause.
例如,使用:
try:
import platform_specific_module
except ImportError:
platform_specific_module = None
一个空的except:子句将捕获SystemExit和KeyboardInterrupt
异常,这使得中断程序更加困难使用Control-C,
并可以掩盖其他问题。如果您想捕获所有表示程序错误的异常
,请使用Exception除外:(裸除
等效于BaseException:除外)。
A bare except: clause will catch SystemExit and KeyboardInterrupt exceptions, making it harder to interrupt a program with Control-C, and can disguise other problems. If you want to catch all exceptions that signal program errors, use except Exception: (bare except is equivalent to except BaseException: ).
一个好的经验法则是将仅使用'except'子句限制为两个
情况:
A good rule of thumb is to limit use of bare 'except' clauses to two cases:
如果异常处理程序将打印输出或记录回溯;
If the exception handler will be printing out or logging the traceback; at least the user will be aware that an error has occurred.
如果代码需要执行一些清理工作,但随后让异常通过raise向上传播,则至少用户会意识到发生了错误。试试...最后可以是一种更好的
处理这种情况的方法。
If the code needs to do some cleanup work, but then lets the exception propagate upwards with raise . try...finally can be a better way to handle this case.
如何用这种好方法?
您引用的PEP8指南建议,在记录错误的情况下,可以在情况下使用裸露的异常。我认为您应该涵盖尽可能多的例外/知道如何处理,然后记录其余例外并通过
,例如
The PEP8 guide you quote suggests that it is okay to use a bare exception in your case provided you are logging the errors. I would think that you should cover as many exceptions as you can/know how to deal with and then log the rest and pass
, e.g.
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)