在Python中,是否可以爲一個try
語句使用多個except
語句?如:Python:一個嘗試多個例外
try:
#something1
#something2
except ExceptionType1:
#return xyz
except ExceptionType2:
#return abc
在Python中,是否可以爲一個try
語句使用多個except
語句?如:Python:一個嘗試多個例外
try:
#something1
#something2
except ExceptionType1:
#return xyz
except ExceptionType2:
#return abc
是的,這是可能的。
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)
假設something1是行'except something1'中的異常類? – 2011-05-23 10:12:18
@Sentinel - 夠公平的。如果我濫用社區,請道歉。 – Eva611 2011-05-23 10:24:14
@ Eva611:不要道歉。 (1)嘗試一下。 (2)發佈你的問題的答案。 – 2011-05-23 11:11:34