【问题标题】:Using multiple exceptions in python在python中使用多个异常
【发布时间】:2013-11-29 14:23:47
【问题描述】:
有没有办法在 python 中使用多个异常?如下代码:
try:
#mycode
except AttributeError TypeError ValueError:
#my exception
我的意思是AttributeErrorTypeErrorValueError如何互相使用?
【问题讨论】:
标签:
python
exception
python-3.x
exception-handling
【解决方案1】:
使用元组:
try:
# mycode
except (AttributeError, TypeError, ValueError):
# catches any of the three exception types above
引用reference try statement documentation:
当try 套件中发生异常时,将开始搜索异常处理程序。此搜索依次检查 except 子句,直到找到与异常匹配的子句。
[...]
对于带有表达式的 except 子句,该表达式被求值,如果结果对象与异常“兼容”,则该子句匹配异常。如果一个对象是异常对象的类或基类或包含与异常兼容的项的元组,则该对象与异常兼容。
强调我的。