2014-04-08 29 views
2

檢查有關的異常處理下面的代碼在python爲什麼在函數中返回抑制引發的異常?

class myException(Exception): 
    def __str__(self): 
     return 'this is my exception' 
class myException2(Exception): 
    def __str__(self): 
     return 'this is my exception 2' 
def myfunc(): 
    try: 
     raise myException2 
     print('after exception') 
    except myException: 
     a = 'exception occur' 
     print(a) 
    else: 
     a = 'exception doesn\'t occur' 
     print(a) 
    finally: 
     a = 'no matter exception occurs or not' 
     print(a) 
     return a 

然後乳寧MYFUNC()將沒有任何異常輸出彈出

no matter exception occurs or not 

但如果在最後條款「返回」代碼評論,輸出將捕獲未處理的myException2,

no matter exception occurs or not 
--------------------------------------------------------------------------- 
myException2        Traceback (most recent call last) 
<ipython-input-140-29dfc9311b33> in <module>() 
----> 1 myfunc() 

<ipython-input-139-ba35768198b8> in myfunc() 
     1 def myfunc(): 
     2  try: 
----> 3   raise myException2 
     4   print('after exception') 
     5  except myException: 

myException2: this is my exception 2 

爲什麼返回碼對於採集卡非常重要異常?

回答

4

直接從python docs

如果最後存在時,它指定一個「清除」處理程序。執行try 子句,包括任何except和else子句。如果任何一個條款中發生異常並且未處理, 異常將暫時保存。 finally子句被執行。如果 有一個保存的異常,它會在finally 子句的末尾重新生成。 如果最後條款引發了另一個異常或執行 退貨或break語句,保存異常被丟棄:

這是有道理的,因爲打印這個錯誤在最後發言結束時會發生。您可以提前退出該語句,以便不應該執行打印。

+0

非常感謝。 – Lansiz

相關問題