我們有內部的try節選像除Python外的內部嘗試 - 流程如何工作?
try:
try: (problem here)
except: (goes here)
except: (will it go here) ??
是這樣的當期的流動嘗試節選?如果在外部嘗試塊內部捕獲異常,它是錯誤還是非錯誤?
我們有內部的try節選像除Python外的內部嘗試 - 流程如何工作?
try:
try: (problem here)
except: (goes here)
except: (will it go here) ??
是這樣的當期的流動嘗試節選?如果在外部嘗試塊內部捕獲異常,它是錯誤還是非錯誤?
不,它不會在第二個,除非第一個也引發異常。
當你進入except
條款時,你幾乎可以說「異常已被捕獲,我會處理它」,除非你重新拋出異常。例如,此構造通常可能非常有用:
try:
some_code()
try:
some_more_code()
except Exception as exc:
fix_some_stuff()
raise exc
except Exception as exc:
fix_more_stuff()
這使您可以對相同的異常有多個「修復」層。
它不會達到外界except
,除非你是一箇中提出了另一個例外,像這樣:
try:
try:
[][1]
except IndexError:
raise AttributeError
except AttributeError:
print("Success! Ish")
除非內except
塊中引發一個例外外塊配件,它不會作爲計一個錯誤。
權利,例外內的例外轉到主區塊 – Nishant 2013-02-26 15:00:42
該錯誤不會觸及外部Except
。你可以像這樣測試它:
x = 'my test'
try:
try: x = int(x)
except ValueError: print 'hit error in inner block'
except: print 'hit error in outer block'
這將只打印'hit error in inner block'
。
但是,說你內Try
/Except
塊後,一些其他的代碼,這引發了一個錯誤:
x, y = 'my test', 0
try:
try: x = int(x)
except ValueError: print 'x is not int'
z = 10./y
except ZeroDivisionError: print 'cannot divide by zero'
這將同時打印'x is not int'
和'cannot divide by zero'
。
這是一個senario。 – Nishant 2013-02-26 15:00:14
故事的道德:*不要*創建毯子,除了子句。只捕捉*特定的*例外。 – 2013-02-26 13:29:26