2011-05-23 29 views
74

在Python中,是否可以爲一個try語句使用多個except語句?如:Python:一個嘗試多個例外

try: 
#something1 
#something2 
except ExceptionType1: 
#return xyz 
except ExceptionType2: 
#return abc 
+0

假設something1是行'except something1'中的異常類? – 2011-05-23 10:12:18

+1

@Sentinel - 夠公平的。如果我濫用社區,請道歉。 – Eva611 2011-05-23 10:24:14

+3

@ Eva611:不要道歉。 (1)嘗試一下。 (2)發佈你的問題的答案。 – 2011-05-23 11:11:34

回答

149

是的,這是可能的。

try: 
    ... 
except FirstException: 
    handle_first_one() 

except SecondException: 
    handle_second_one() 

except (ThirdException, FourthException, FifthException) as e: 
    handle_either_of_3rd_4th_or_5th() 

except Exception: 
    handle_all_other_exceptions() 

參見:http://docs.python.org/tutorial/errors.html

的「爲」關鍵字用於誤差分配給一個變量使得誤差可以在代碼被更徹底調查以後。另請注意,python 3中需要三重異常情況的括號。此頁面有更多信息:Catch multiple exceptions in one line (except block)

+28

如果你想在兩種情況下都做同樣的事情,那就是'except(SomeError,OtherError):'。不回答OP問題,但可能會幫助一些通過Google訪問的人。 – Mark 2013-09-25 14:43:49

+3

@Mark:好的一點,補充說明一下。 – vartec 2013-09-25 14:58:49

+0

例如,如果您必須將數據結構的多個版本轉換爲新的結構,則例如在更新代碼版本時,可以嵌套try..excepts。 – 2015-12-04 14:00:12