我在想你是否可以重新提出一個(特定的)捕獲的異常,並讓它被後面的(一般)捕獲,除了在相同的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方式是什麼?
(我知道有一個建議,沒有實現「有條件的除外」,這可能已經解決了這個)
因此,您希望能夠從'IOError'塊除外到'except Exception'塊之外?據我所知,這是不可能的,只有一個'except'塊(或'else'塊)運行給定的'try'。你可以把所有的東西包裝在另一個'try'中,除去除了Exception之外的內部'''',這意味着除了特殊處理的'IOError'外,''外'try'''除''外。 – jonrsharpe
這就是我想要做的,我擔心只有一個除外是可能的。我希望有一個更優雅的解決方案,就像嵌套的else /代碼複製 – OverlordAlex