2016-05-13 63 views
0

例如:如何檢測python中的try塊是否引發異常?

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 

實際的問題是,我有一個代碼塊中,我在嘗試有超時錯誤 - 除了塊。每次發生TimeOut錯誤時,我都會在try中捕獲它 - 除了block和發出5次重試。此TimeOut錯誤具有一個對象,該對象將收集錯誤跟蹤以防引發異常,以便在調試問題時提供更多上下文。但每次在try塊中引發異常時,該調用都會調用函數,並最終收集該錯誤的跟蹤信息,這是我不想要的,因爲我只是在除了塊之外再次執行操作。是否有任何方法在Python使用檢查或其他模塊,可以告訴我,異常是從嘗試塊引發?

+3

你認爲除了發生什麼? –

+3

看起來你正在試圖濾除可能未捕獲的異常。那是對的嗎?你能否進一步解釋你爲什麼要這樣做? –

+3

看起來好像你希望你的異常在被try塊阻塞時有一個行爲,如果沒有被捕獲到另一個行爲,但它們只是一個信號 - 異常不應該有副作用。 –

回答

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編寫的,以 簡化向任何事物添加重試行爲的任務。

相關問題