开发者

Python: One Try Multiple Except

开发者 https://www.devze.com 2023-03-07 14:12 出处:网络
In Python, is it possible to have multiple except statements for one try statement? Such as : try: #something1

In Python, is it possible to have multiple except statements for one try statement? Such as :

try:
 #something1
 #something2
except ExceptionType开发者_Go百科1:
 #return xyz
except ExceptionType2:
 #return abc


Yes, it is possible.

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()

See: http://docs.python.org/tutorial/errors.html

The "as" keyword is used to assign the error to a variable so that the error can be investigated more thoroughly later on in the code. Also note that the parentheses for the triple exception case are needed in python 3. This page has more info: Catch multiple exceptions in one line (except block)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号