在python中使用多个异常

2024-04-19 02:48:51 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有一种方法可以在python中使用多个异常?如下代码:

try:
   #mycode
except AttributeError TypeError ValueError:
   #my exception

我的意思是如何互相使用AttributeErrorTypeErrorValueError?在


Tags: 方法代码myexceptionattributeerrortryvalueerrorexcept
1条回答
网友
1楼 · 发布于 2024-04-19 02:48:51

使用元组:

try:
   # mycode
except (AttributeError, TypeError, ValueError):
   # catches any of the three exception types above

引用reference ^{} statement documentation

When an exception occurs in the try suite, a search for an exception handler is started. This search inspects the except clauses in turn until one is found that matches the exception.
[...]
For an except clause with an expression, that expression is evaluated, and the clause matches the exception if the resulting object is “compatible” with the exception. An object is compatible with an exception if it is the class or a base class of the exception object or a tuple containing an item compatible with the exception.

强调我的。在

相关问题 更多 >