相关疑难解决方法(0)

如何防止尝试捕获python中的每一行?

我连续排了很多行,这可能会引发异常,但无论如何,它仍应继续下一行.如何在不单独尝试捕获可能引发异常的每个语句的情况下执行此操作?

try:
    this_may_cause_an_exception()
    but_I_still_wanna_run_this()
    and_this()
    and_also_this()
except Exception, e:
    logging.exception('An error maybe occured in one of first occuring functions causing the others not to be executed. Locals: {locals}'.format(locals=locals()))
Run Code Online (Sandbox Code Playgroud)

让我们看一下上面的代码,所有函数都可能抛出异常,但它仍然应该执行下一个函数,无论它是否抛出异常.这样做有什么好办法吗?

我不想这样做:

try:
    this_may_cause_an_exception()
except:
    pass
try:
    but_I_still_wanna_run_this()
except:
    pass
try:
    and_this()
except:
    pass
try:
    and_also_this()
except:
    pass
Run Code Online (Sandbox Code Playgroud)

我认为代码应该仍然继续在异常之后运行,只有当异常是关键的(计算机将烧毁或整个系统将搞砸,它应该停止整个程序,但对于许多小事情也会抛出异常,例如连接我通常没有任何异常处理问题,但在这种情况下,我使用的是第三方库,它很容易抛出小事的异常.

在查看了m4spy的答案后,我认为不可能有一个装饰器,即使其中一个引发异常,它也会让函数中的每一行都执行.

像这样的东西会很酷:

def silent_log_exceptions(func):
    @wraps(func)
    def _wrapper(*args, **kwargs):
        try:
            func(*args, **kwargs)
        except Exception:
            logging.exception('...')
            some_special_python_keyword # which causes it to continue executing the next line
    return _wrapper
Run Code Online (Sandbox Code Playgroud)

或类似的东西:

def silent_log_exceptions(func):
    @wraps(func)
    def _wrapper(*args, …
Run Code Online (Sandbox Code Playgroud)

python exception-handling exception

18
推荐指数
1
解决办法
3441
查看次数

标签 统计

exception ×1

exception-handling ×1

python ×1