Python: One Try Multiple Except(Python:一次尝试多次,除了)
问题描述
在 Python 中,一个 try
语句是否可以有多个 except
语句?如:
In Python, is it possible to have multiple except
statements for one try
statement? Such as :
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
as"关键字用于将错误分配给变量,以便稍后在代码中更彻底地调查错误.另请注意,python 3 中需要三重异常情况的括号.此页面包含更多信息:一行捕获多个异常(block除外)
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)
这篇关于Python:一次尝试多次,除了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!