繁体   English   中英

如何检测是否从python中的try块引发了异常?

[英]How to detect if an exception has been raised from a try block in python?

例如:

class ExceptionMeta(type):
  def __call__(cls, *args, **kwargs):
    if exception_raised_from_try_block:
       do_something
    else:
       do_something_else

class TimeOutError(metaclass = ExceptionMeta):
  pass

try:
  raise TimeOutError
except Exception as e:
  pass

实际的问题是我有一个代码块,其中try -except块中出现超时错误。 每次引发TimeOut错误时,我都会尝试-除阻止并发出重试5次外,将其捕获。 此超时错误具有一个对象,该对象将在引发异常的情况下收集错误跟踪,以便在调试问题时提供更多上下文。 但是每次在try块中引发异常时,调用都会转到call函数,并且最终会收集我不想要的错误的跟踪信息,因为我只是在except块中再次尝试

python中是否有使用检查或其他模块的任何方式可以告诉我从try块引发了异常?

所以你的问题是重试代码块...

假设您有一些类似的代码:

import random

def do_something_unreliable(msg="we have landed"):
    if random.randint(0, 10) > 1:
        raise Exception("Timed out...")
    else:
        return "Houston, {0}.".format(msg)

您可以执行以下操作重试5次:

for attempt in range(1, 5):
    try:
        do_something_unreliable()
    except Exception:
        # print("timeout, trying again...")
        pass
    else:
        break
else:
    do_something_unreliable()

您可以通过以下方法使其可重用:

def retry(fn, args=None, kwargs=None, times=5, verbose=False, exceptions=None):
    if args is None:
        args = []
    if kwargs is None:
        kwargs = {}
    if exceptions is None:
        exceptions = (Exception,)
    for attempt in range(1, times):
        try:
            return fn(*args, **kwargs)
        except exceptions as e:
            if verbose:
                print("Got exception {0}({1}), retrying...".format(
                         e.__class__.__name__, e))
    return fn(*args, **kwargs)

然后您可以编写:

>>> retry(do_something_unreliable, verbose=True)
Got exception Exception(Timed out...), retrying...
Got exception Exception(Timed out...), retrying...
Got exception Exception(Timed out...), retrying...
'Houston, we have landed.'

>>> retry(do_something_unreliable, ['we are lucky'], verbose=True)
Got exception Exception(Timed out...), retrying...
Got exception Exception(Timed out...), retrying...
'Houston, we are lucky.'

您还可以查看retrying装饰器:

重试是用Python编写的Apache 2.0许可的通用重试库,用于简化将重试行为添加到几乎所有内容的任务。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM