【问题标题】: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 子句,该表达式被求值,如果结果对象与异常“兼容”,则该子句匹配异常。如果一个对象是异常对象的类或基类或包含与异常兼容的项的元组,则该对象与异常兼容。

    强调我的。

    【讨论】:

      猜你喜欢
      • 2020-10-05
      • 2019-07-20
      • 2021-07-06
      • 2013-01-05
      • 1970-01-01
      • 2018-12-24
      • 1970-01-01
      • 2020-06-20
      • 1970-01-01
      相关资源
      最近更新 更多