2015-10-19 29 views
5

我在想你是否可以重新提出一個(特定的)捕獲的異常,並讓它被後面的(一般)捕獲,除了在相同的try-except外。作爲一個例子,我想用特定的IOError做一些事情,但是如果它不是預期的IOError,那麼這個異常應該像其他錯誤一樣處理。我最初嘗試過的:Python'except'fall-through

try: 
    raise IOError() 
except IOError as ioerr: 
    if ioerr.errno == errno.ENOENT: 
     # do something with the expected err 
    else: 
     # continue with the try-except - should be handled like any other error 
     raise 
except Exception as ex: 
    # general error handling code 

但是,這不起作用:raise會重新引發try-except之外的異常。 寫這個以獲得期望的異常'fall-through'行爲的pythonic方式是什麼?

(我知道有一個建議,沒有實現「有條件的除外」,這可能已經解決了這個)

+1

因此,您希望能夠從'IOError'塊除外到'except Exception'塊之外?據我所知,這是不可能的,只有一個'except'塊(或'else'塊)運行給定的'try'。你可以把所有的東西包裝在另一個'try'中,除去除了Exception之外的內部'''',這意味着除了特殊處理的'IOError'外,''外'try'''除''外。 – jonrsharpe

+0

這就是我想要做的,我擔心只有一個除外是可能的。我希望有一個更優雅的解決方案,就像嵌套的else /代碼複製 – OverlordAlex

回答

1

我不是在寫pythonically的專家,但我認爲一個明顯的方法(如果你知道你期待一個特定類型的異常),是使用嵌套的異常處理:

try: 
    try: 
     raise IOError() 
    except IOError as ioerr: 
     if ioerr.errno == errno.ENOENT: 
      # do something with the expected err 
     else: 
      # pass this on to higher up exception handling 
      raise 

except Exception as ex: 
    # general error handling code 

我知道你的意見,你不希望別人嵌套的 - 我不知道如果嵌套異常處理在您的書中同樣糟糕,但至少您可以避免代碼重複。

+0

這是一個很好的方法,一旦你看到它,它確實顯而易見。非常酷的主意! – iFreilicht

1

所以,我在這裏也一樣,在回顧可用的解決方案之後,我將繼續捕捉父異常,然後測試具體細節。在我的情況下,我正在使用DNS模塊。

try: 
    answer = self._resolver.query(name, 'NS') 
except dns.exception.DNSException, e: #Superclass of exceptions tested for 
    if isinstance(e, dns.resolver.NXDOMAIN): 
     #Do Stuff 
    elif isinstance(e, dns.resolver.NoAnswer): 
     # Do other stuff 
    else: 
     # Do default stuff