Using multiple exceptions in python

巧了我就是萌 提交于 2021-01-27 14:27:54

问题


Is there a way to use multiple exceptions in python? Like code below:

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

What I mean is how to use AttributeError TypeError ValueError with each other?


回答1:


Use a tuple:

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

Quoting the reference try 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.

Emphasis mine.



来源:https://stackoverflow.com/questions/20287886/using-multiple-exceptions-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!