Python:一个尝试多个除外

问题描述:

在Python中,一个 try 语句可以有多个语句之外吗?如:

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

try:
 #something1
 #something2
except something1:
 #return xyz
except something2:
 #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:
   handle_all_other_exceptions()

请参阅: http://docs.python.org/tutorial/errors.html

as关键字用于将错误分配给变量,以便稍后在代码中更详细地对错误进行调查。另请注意,python 3中需要三重异常情况的括号。此页面有更多的信息:在一行(块除外)中捕获多个异常

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)