有没有办法在python中使用多个异常?如下代码:
try:
#mycode
except AttributeError TypeError ValueError:
#my exception
我的意思是如何在彼此之间使用
AttributeError
TypeError
ValueError
? 最佳答案
使用元组:
try:
# mycode
except (AttributeError, TypeError, ValueError):
# catches any of the three exception types above
引用reference
try
statement documentation:当
try
套件中发生异常时,将开始搜索异常处理程序。此搜索依次检查except子句,直到找到与异常匹配的子句。[…]
对于包含表达式的except子句,将计算该表达式,如果结果对象与异常“兼容”,则该子句将匹配异常。如果对象是异常对象的类或基类,或者是包含与异常兼容的项的元组,则该对象与异常兼容。
强调我的。