一个有多个例外的尝试块

问题描述 投票:0回答:1

在Python中,一个

except
语句是否可以有多个
try
语句?如:

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

同理处理多个异常的情况见Catch multiple exceptions in one line (except block)

python syntax exception
1个回答
550
投票

是的,这是可能的。

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

“as”关键字用于将错误分配给变量,以便稍后可以在代码中更彻底地调查错误。另请注意,python 3 中需要三重异常情况的括号。此页面有更多信息:Catch multiple exceptions in one line (except block)

© www.soinside.com 2019 - 2024. All rights reserved.