在 Python 中,一个 try
语句是否可以有多个 except
语句?如 :
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 中需要三重异常情况的括号。此页面包含更多信息:Catch multiple exceptions in one line (except block)
不定期副业成功案例分享
except (SomeError, OtherError):
。不回答 OP 问题,但可能会帮助一些通过 Google 到达这里的人。except Exception:
而不是普通的except:
。 (普通的 except 甚至会捕获SystemExit
和KeyboardInterrupt
这通常不是你想要的)e
做一些事情,因为您给它起了一个名字:)