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

时间:2016-05-13 14:25:33

标签: python exception

例如:

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错误。每次引发TimeOut错误时,我都会在try - except块中捕获它并发出5次重试。此TimeOut错误有一个对象,它将在引发异常时收集错误跟踪,以便在调试问题时提供更多上下文。但是每次在try块中引发异常时,调用都会调用函数,并且最终会收集我不想要的错误的跟踪,因为我只是在except块中再次重试

有没有办法在python中使用检查或其他模块可以告诉我异常是从try块引出的?

1 个答案:

答案 0 :(得分:0)

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

假设您有一些代码:

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装饰器:

  

Retrying是Apache 2.0   许可的通用重试库,用Python编写,到   简化了将重试行为添加到任何事情的任务。